44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { WebSocket, RawData } from "ws";
|
|
import { SocketVM } from "./SocketVM";
|
|
|
|
import * as Shared from "@socketcomputer/shared";
|
|
|
|
export class VMUser {
|
|
public connection: WebSocket;
|
|
public address: string;
|
|
public username: string = "";
|
|
public vm: SocketVM|null = null;
|
|
|
|
|
|
constructor(connection: WebSocket, address: string) {
|
|
this.connection = connection;
|
|
this.address = address;
|
|
|
|
this.connection.on('message', async (data: RawData, isBinary: boolean) => {
|
|
if (!isBinary) this.connection.close(1000, "No");
|
|
await this.vm?.OnWSMessage(this, data as Buffer);
|
|
});
|
|
|
|
this.connection.on('close', async (code: number, reason: Buffer) => {
|
|
await this.vm?.RemUser(this);
|
|
});
|
|
}
|
|
|
|
async SendMessage(messageGenerator: (encoder: Shared.MessageEncoder) => ArrayBuffer) {
|
|
await this.SendBuffer(messageGenerator(new Shared.MessageEncoder()));
|
|
}
|
|
|
|
async SendBuffer(buffer: Buffer|ArrayBuffer): Promise<void> {
|
|
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)}`;
|
|
}
|
|
}
|