UNPKG

@hathora/client-sdk

Version:

![Hathora Logo](https://user-images.githubusercontent.com/7004280/223056895-c16419d2-2b91-4013-82f0-7616c84d31b7.svg)

72 lines (71 loc) 2.16 kB
import WebSocket from "isomorphic-ws"; export class HathoraConnection { roomId; connectionInfo; socket; messageListeners = []; closeListeners = []; stringEncoder = new TextEncoder(); stringDecoder = new TextDecoder(); constructor(roomId, connectionInfo) { this.roomId = roomId; this.connectionInfo = connectionInfo; } onMessage(listener) { this.messageListeners.push(listener); } onMessageString(listener) { this.messageListeners.push((buf) => { listener(this.stringDecoder.decode(buf)); }); } onMessageJson(listener) { this.onMessageString((str) => { listener(JSON.parse(str)); }); } onClose(listener) { this.closeListeners.push(listener); } async connect(token) { const { host, port, transportType } = this.connectionInfo; this.socket = new WebSocket(`${transportType === "tls" ? "wss" : "ws"}://${host}:${port}/${this.roomId}?token=${token}`); this.socket.binaryType = "arraybuffer"; return new Promise((resolve, reject) => { this.socket.onopen = () => { resolve(); }; this.socket.onclose = (e) => { reject(e.reason); this._onClose(e); }; this.socket.onmessage = ({ data }) => { if (!(data instanceof ArrayBuffer)) { throw new Error("Unexpected data type: " + typeof data); } this._onMessage(data); }; }); } write(data) { this.socket?.send(data); } writeString(data) { this.write(this.stringEncoder.encode(data)); } writeJson(data) { this.writeString(JSON.stringify(data)); } disconnect(code) { if (code === undefined) { this.socket.onclose = () => { }; } this.socket.close(code); } _onMessage(data) { this.messageListeners.forEach((listener) => listener(data)); } _onClose(e) { this.closeListeners.forEach((listener) => listener(e)); } }