Created
December 31, 2024 19:30
-
-
Save skang2-sc/53d25281e77f1150888f9e17907b3bc9 to your computer and use it in GitHub Desktop.
WebSocketConnection Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Event from "SpectaclesInteractionKit/Utils/Event"; | |
const HOST = "wss://[APP_NAME].herokuapp.com"; | |
export class WebSocketConnection { | |
private remoteServiceModule: RemoteServiceModule = require("LensStudio:RemoteServiceModule"); | |
private webSocket: WebSocket; | |
private onMessageEvent = new Event<WebSocketMessageEvent>(); | |
public readonly onMessage = this.onMessageEvent.publicApi(); | |
private onErrorEvent = new Event<WebSocketErrorEvent>(); | |
public readonly onError = this.onErrorEvent.publicApi(); | |
private onOpenEvent = new Event<WebSocketEvent>(); | |
public readonly onOpen = this.onOpenEvent.publicApi(); | |
private onCloseEvent = new Event<WebSocketCloseEvent>(); | |
public readonly onClose = this.onCloseEvent.publicApi(); | |
private user: string; | |
private room: string; | |
private displayName: string; | |
constructor() { | |
this.connect(); | |
} | |
private connect() { | |
this.webSocket = this.remoteServiceModule.createWebSocket(HOST); | |
this.webSocket.addEventListener("error", this._onError.bind(this)); | |
this.webSocket.addEventListener("message", this._onMessage.bind(this)); | |
this.webSocket.addEventListener("open", this._onOpen.bind(this)); | |
this.webSocket.addEventListener("close", this._onClose.bind(this)); | |
} | |
private _onOpen(event: WebSocketEvent) { | |
print("WebSocket opened"); | |
this.onOpenEvent.invoke(event); | |
} | |
private _onClose(event: WebSocketCloseEvent) { | |
print("WebSocket closed"); | |
this.onCloseEvent.invoke(event); | |
} | |
private _onError(event: WebSocketErrorEvent) { | |
this.onErrorEvent.invoke(event); | |
} | |
private _onMessage(event: WebSocketMessageEvent) { | |
print("Received Message"); | |
this.onMessageEvent.invoke(event); | |
} | |
send(data: any) { | |
if (this.webSocket.readyState !== WebSocketReadyState.OPEN) return; | |
this.webSocket.send(data); | |
} | |
close() { | |
this.webSocket.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment