Add handshake data handling and tests

This commit is contained in:
Hamcha 2019-09-06 14:32:51 +02:00
parent 6f8fac89aa
commit 03e295b41e
Signed by: hamcha
GPG key ID: 44AD3571EB09A39E
3 changed files with 32 additions and 3 deletions

View file

@ -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) {

View file

@ -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) {

View file

@ -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);
});
});