socketcomputer/backend/src/VMUser.ts

45 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-04-07 08:37:43 -04:00
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 = "";
2024-04-07 08:37:43 -04:00
public vm: SocketVM|null = null;
2024-04-07 08:37:43 -04:00
constructor(connection: WebSocket, address: string) {
this.connection = connection;
this.address = address;
2024-04-07 08:37:43 -04:00
this.connection.on('message', async (data: RawData, isBinary: boolean) => {
if (!isBinary) this.connection.close(1000, "No");
await this.vm?.OnWSMessage(this, data as Buffer);
});
2024-04-07 08:37:43 -04:00
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()));
}
2024-04-07 08:37:43 -04:00
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)}`;
}
}