diff --git a/src/network/server.ts b/src/network/server.ts index d3aec55..f49d70a 100644 --- a/src/network/server.ts +++ b/src/network/server.ts @@ -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({ 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(player.conn, { kind: "ok", what: "leave-req" }); + + // Close connection with player + player.conn.close(); + + // Notify other players + this.broadcast({ + 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; diff --git a/src/network/types.ts b/src/network/types.ts index d8d0c47..a84f039 100644 --- a/src/network/types.ts +++ b/src/network/types.ts @@ -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;