]> git.cworth.org Git - lmno-server/blob - game.js
Add common handle_events code to the Game class
[lmno-server] / game.js
1 /* Base class providing common code for game engine implementations. */
2 class Game {
3   constructor(name) {
4     this.name = name;
5     this.clients = [];
6     this.next_client_id = 1;
7   }
8
9   add_client(response) {
10     const id = this.next_client_id;
11     this.clients.push({id: id,
12                        response: response});
13     this.next_client_id++;
14
15     return id;
16   }
17
18   remove_client(id) {
19     this.clients = this.clients.filter(client => client.id !== id);
20   }
21
22   /* Send a string to all clients */
23   broadcast_string(str) {
24     this.clients.forEach(client => client.response.write(str + '\n'));
25   }
26
27   /* Send an event to all clients.
28    *
29    * An event has both a declared type and a separate data block.
30    * It also ends with two newlines (to mark the end of the event).
31    */
32   broadcast_event(type, data) {
33     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
34   }
35
36   handle_events(request, response) {
37     /* These headers will keep the connection open so we can stream events. */
38     const headers = {
39       "Content-type": "text/event-stream",
40       "Connection": "keep-alive",
41       "Cache-Control": "no-cache"
42     };
43     response.writeHead(200, headers);
44
45     /* Add this new client to our list of clients. */
46     const id = this.add_client(response);
47
48     /* And queue up cleanup to be triggered on client close. */
49     request.on('close', () => {
50       this.remove_client(id);
51     });
52   }
53
54 }
55
56 module.exports = Game;