From 03e295b41eed4acf1b62f11328997752c44c5f24 Mon Sep 17 00:00:00 2001 From: Hamcha Date: Fri, 6 Sep 2019 14:32:51 +0200 Subject: [PATCH] Add handshake data handling and tests --- src/network/Client.ts | 16 +++++++++++++--- src/network/PeerServer.ts | 3 +++ src/tests/unit/network.spec.ts | 16 ++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/network/Client.ts b/src/network/Client.ts index 2ac333a..a6a43c1 100644 --- a/src/network/Client.ts +++ b/src/network/Client.ts @@ -1,19 +1,29 @@ -import { PeerMetadata, NetworkMessage, PasswordResponse } from "./types"; +import { + PeerMetadata, + NetworkMessage, + PasswordResponse, + RoomInfo +} from "./types"; import EventEmitter from "eventemitter3"; export abstract class Client extends EventEmitter { public metadata: PeerMetadata; - public players: string[]; + public players!: string[]; + public roomInfo!: RoomInfo; public constructor(metadata: PeerMetadata) { super(); this.metadata = metadata; - this.players = []; } protected _received(data: NetworkMessage) { this.emit("data", data); switch (data.kind) { + // Server is sending over player list and room info + case "room-info": + this.roomInfo = data.room; + this.players = data.players; + break; // Someone changed name (or was forced to) case "rename": if (data.oldname == this.metadata.name) { diff --git a/src/network/PeerServer.ts b/src/network/PeerServer.ts index 40da2ce..bfadda2 100644 --- a/src/network/PeerServer.ts +++ b/src/network/PeerServer.ts @@ -59,6 +59,9 @@ export class PeerServer extends EventEmitter { players }; + local.players = Object.keys(this.players); + local.roomInfo = this.room.info; + // Setup peer this.peer = customPeer ? customPeer : new Peer(); this.peer.on("open", function(id) { diff --git a/src/tests/unit/network.spec.ts b/src/tests/unit/network.spec.ts index 3a5a8a5..dfe425d 100644 --- a/src/tests/unit/network.spec.ts +++ b/src/tests/unit/network.spec.ts @@ -132,4 +132,20 @@ describe("network/PeerClient", () => { expect(msg.message).toEqual(hellomsg); }); }); + + test("Client internal player list gets correctly updated", async () => { + const mox = new MockHelper(); + const hook = new EventHook(); + const local = new LocalClient({ name: "server-player" }); + const server = mox.createServer(sampleRoom(), "test-server", local); + const client = mox.createClient(); + hook.hookEmitter(local, "player-joined", "client-joined"); + hook.hookEmitter(local, "player-left", "client-left"); + client.connect("test-server"); + await hook.expect("client-joined", 1000); + expect(local.players).toHaveLength(2); + client.leave(); + await hook.expect("client-left", 1000); + expect(local.players).toHaveLength(1); + }); });