]> git.cworth.org Git - lmno-server/commitdiff
Rename broadcast() to broadcast_event() supported by broadcast_string()
authorCarl Worth <cworth@cworth.org>
Sun, 10 May 2020 15:35:21 +0000 (08:35 -0700)
committerCarl Worth <cworth@cworth.org>
Sun, 10 May 2020 15:39:05 +0000 (08:39 -0700)
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

index 1b8dd292e078ebc549ea5f59bf1c2bf6ef068f59..deb0b9c58a44bf17fd3307f46831c8a3009c6d06 100644 (file)
--- 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`);
   }
 }