import { WebSocket } from "ws"; import { SocketVM } from "./SocketVM"; import * as Shared from "@socketcomputer/shared"; export class VMUser { public connection: WebSocket; public address: string; public username: string = ""; private vm: SocketVM; constructor(connection: WebSocket, slot: SocketVM, address: string) { this.connection = connection; this.address = address; this.vm = slot; this.vm.AddUser(this); this.connection.on('message', async (data, isBinary) => { if (!isBinary) this.connection.close(1000); await this.vm.OnWSMessage(this, data as Buffer); }); this.connection.on('close', async () => { console.log('closed'); await this.vm.RemUser(this); }); } async SendMessage(messageGenerator: (encoder: Shared.MessageEncoder) => ArrayBuffer) { await this.SendBuffer(messageGenerator(new Shared.MessageEncoder())); } async SendBuffer(buffer: ArrayBuffer): Promise { return new Promise((res, rej) => { if (this.connection.readyState !== WebSocket.CLOSED) { this.connection.send(buffer); res(); } rej(new Error('connection haves closed')); }); } static GenerateName() { return `guest${Math.floor(Math.random() * (99999 - 10000) + 10000)}`; } }