From a2173a80f7c55b1c6d1fedb9c4afdf77e7cc8e37 Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Sun, 10 May 2020 08:35:21 -0700 Subject: [PATCH] Rename broadcast() to broadcast_event() supported by broadcast_string() The lower-level broadcast_string() simply sends a string to all clients. The higher-level broadcast_event() sends a structured event (with both an event type and a separate data block, as well as ending with two newlines), exactly as clients will be expecting. --- server.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/server.js b/server.js index 1b8dd29..deb0b9c 100644 --- a/server.js +++ b/server.js @@ -25,14 +25,14 @@ class Game { object from new_player with just the subset of fields that we want. */ const player_string = JSON.stringify((({id, name}) => ({id, name}))(new_player)); - this.broadcast("player-register", player_string); + this.broadcast_event("player-register", player_string); } remove_player(id) { const index = this._players.findIndex(player => player.id === id); this._players.splice(index, 1); - this.broadcast("player-deregister", `{"id": ${id}}`); + this.broadcast_event("player-deregister", `{"id": ${id}}`); } remove_all_players() { @@ -47,7 +47,7 @@ class Game { let captor = this._players.find(player => player.id === captor_id); captor.captures.push(captee_id); - this.broadcast("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`); + this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`); } liberate(captee_id) { @@ -86,9 +86,18 @@ class Game { this.clients = this.clients.filter(client => client.id !== id); } - /* Send an event to all clients */ - broadcast(type, data) { - this.clients.forEach(client => client.response.write(`event: ${type}\ndata: ${data}\n\n`)); + /* Send a string to all clients */ + broadcast_string(str) { + this.clients.forEach(client => client.response.write(str + '\n')); + } + + /* Send an event to all clients. + * + * An event has both a declared type and a separate data block. + * It also ends with two newlines (to mark the end of the event). + */ + broadcast_event(type, data) { + this.broadcast_string(`event: ${type}\ndata: ${data}\n`); } } -- 2.43.0