Add leaving

This commit is contained in:
Hamcha 2019-09-05 10:20:27 +02:00
parent dd279573e6
commit 5c65ff1900
Signed by: hamcha
GPG key ID: 44AD3571EB09A39E
2 changed files with 51 additions and 4 deletions

View file

@ -11,7 +11,10 @@ import {
RoomInfoMessage,
Player,
NetworkMessage,
RenameMessage
RenameMessage,
LeaveMessage,
NetworkPlayer,
AckMessage
} from "./types";
import LocalClient from "./local";
@ -133,11 +136,38 @@ export default class PeerServer extends NetworkPeer {
// Notify other players
this.broadcast<JoinMessage>({
kind: "player-joined",
name: conn.metadata.name
name: playerName
});
}
private _received(player: Player, data: NetworkMessage) {}
private removePlayer(player: NetworkPlayer) {
// Tell the player everything's fine
this.send<AckMessage>(player.conn, { kind: "ok", what: "leave-req" });
// Close connection with player
player.conn.close();
// Notify other players
this.broadcast<LeaveMessage>({
kind: "player-left",
name: player.name
});
}
private _received(player: Player, data: NetworkMessage) {
switch (data.kind) {
// Player is leaving!
case "leave-req":
// If we're leaving, end the server
if (player.kind == "local") {
//TODO
} else {
// Remove and disconnect player
this.removePlayer(player);
}
break;
}
}
private get playerCount(): number {
return Object.keys(this.room.players).length;

View file

@ -63,10 +63,13 @@ type DraftInfo = {
export type NetworkMessage =
| PasswordRequest
| PasswordResponse
| LeaveRequest
| ErrorMessage
| RoomInfoMessage
| JoinMessage
| RenameMessage;
| LeaveMessage
| RenameMessage
| AckMessage;
export interface PasswordRequest {
kind: "password-req";
@ -83,17 +86,31 @@ export interface RoomInfoMessage {
players: string[];
}
export interface LeaveRequest {
kind: "leave-req";
}
export interface JoinMessage {
kind: "player-joined";
name: string;
}
export interface LeaveMessage {
kind: "player-left";
name: string;
}
export interface RenameMessage {
kind: "rename";
oldname: string;
newname: string;
}
export interface AckMessage {
kind: "ok";
what: string;
}
export interface ErrorMessage {
kind: "error";
error: string;