From 6b34fe3dfa8e5350705d08ce8c1fd4c865349999 Mon Sep 17 00:00:00 2001 From: Hamcha Date: Mon, 7 Oct 2019 12:22:40 +0200 Subject: [PATCH] Wait for connection and properly clean up players --- src/network/PeerServer.ts | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/network/PeerServer.ts b/src/network/PeerServer.ts index e88ffbf..67e3226 100644 --- a/src/network/PeerServer.ts +++ b/src/network/PeerServer.ts @@ -34,6 +34,12 @@ function nextName(name: string): string { return name.substr(0, i) + (Number(name.slice(i)) + 1); } +function connectionOpen(conn: DataConnection): Promise { + return new Promise(resolve => { + conn.on("open", () => resolve()); + }); +} + export class PeerServer extends EventEmitter { protected peer: Peer; private room: Room; @@ -64,17 +70,21 @@ export class PeerServer extends EventEmitter { // Setup peer this.peer = customPeer ? customPeer : new Peer(); - this.peer.on("open", function(id) { + this.peer.on("open", id => { console.info("Peer ID assigned: %s", id); + this.emit("open", id); }); this.peer.on("connection", conn => { this._connection(conn); }); } - private _connection(conn: DataConnection) { + private async _connection(conn: DataConnection) { const metadata = conn.metadata as PeerMetadata; + // Wait for connection to be open + await connectionOpen(conn); + let player: NetworkPlayer = { kind: "remote", name: metadata.name, @@ -140,6 +150,12 @@ export class PeerServer extends EventEmitter { private addPlayer(player: NetworkPlayer) { const playerName = player.name; + + // Hacky: Give player list before this player was added, so join + // message doesn't mess things up later + const players = Object.keys(this.room.players); + + // Add player to room this.room.players[playerName] = player; // Start listening for new messages @@ -148,6 +164,10 @@ export class PeerServer extends EventEmitter { this._received.bind(this, this.room.players[playerName]) ); + player.conn.on("error", err => { + throw err; + }); + // Send the player info about the room this.send(player, { kind: "room-info", @@ -155,7 +175,7 @@ export class PeerServer extends EventEmitter { ...this.room.info, password: "" }, - players: Object.keys(this.room.players) + players }); // Notify other players @@ -172,6 +192,9 @@ export class PeerServer extends EventEmitter { // Close connection with player player.conn.close(); + // Remove player from player list + delete this.room.players[player.name]; + // Notify other players this.broadcast({ kind: "player-left",