From e19e6b890e12ea63c8b57811fdcf3bb74fd58041 Mon Sep 17 00:00:00 2001 From: Sindre Vatnaland <69798990+SindreVatnaland@users.noreply.github.com> Date: Sat, 13 Jan 2024 10:35:14 +0100 Subject: [PATCH] enet fix --- src/console/dolphinConnection.ts | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/console/dolphinConnection.ts b/src/console/dolphinConnection.ts index d658eef9..8b44ef35 100644 --- a/src/console/dolphinConnection.ts +++ b/src/console/dolphinConnection.ts @@ -14,12 +14,14 @@ export enum DolphinMessageType { export class DolphinConnection extends EventEmitter implements Connection { private ipAddress: string; + private enet: any; private port: number; private connectionStatus = ConnectionStatus.DISCONNECTED; private gameCursor = 0; private nickname = "unknown"; private version = ""; private peer: any | null = null; + private client: any | null = null; public constructor() { super(); @@ -27,6 +29,19 @@ export class DolphinConnection extends EventEmitter implements Connection { this.port = Ports.DEFAULT; } + private async initClient() { + if (this.enet) { + return; + } + this.enet = await import("enet"); + this.client = this.enet.createClient({ peers: MAX_PEERS, channels: 3, down: 0, up: 0 }, (err: any) => { + if (err) { + console.error(err); + return; + } + }); + } + /** * @returns The current connection status. */ @@ -53,20 +68,12 @@ export class DolphinConnection extends EventEmitter implements Connection { } public async connect(ip: string, port: number): Promise { + await this.initClient(); console.log(`Connecting to: ${ip}:${port}`); this.ipAddress = ip; this.port = port; - const enet = await import("enet"); - // Create the enet client - const client = enet.createClient({ peers: MAX_PEERS, channels: 3, down: 0, up: 0 }, (err) => { - if (err) { - console.error(err); - return; - } - }); - - this.peer = client.connect( + this.peer = this.client?.connect( { address: this.ipAddress, port: this.port, @@ -94,7 +101,7 @@ export class DolphinConnection extends EventEmitter implements Connection { type: "connect_request", cursor: this.gameCursor, }; - const packet = new enet.Packet(JSON.stringify(request), enet.PACKET_FLAG.RELIABLE); + const packet = new this.enet.Packet(JSON.stringify(request), this.enet.PACKET_FLAG.RELIABLE); this.peer.send(0, packet); });