1 /* Base class providing common code for game engine implementations. */
6 this.next_client_id = 1;
10 const id = this.next_client_id;
11 this.clients.push({id: id,
13 this.next_client_id++;
19 this.clients = this.clients.filter(client => client.id !== id);
22 /* Send a string to all clients */
23 broadcast_string(str) {
24 this.clients.forEach(client => client.response.write(str + '\n'));
27 /* Send an event to all clients.
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).
32 broadcast_event(type, data) {
33 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
36 handle_events(request, response) {
37 /* These headers will keep the connection open so we can stream events. */
39 "Content-type": "text/event-stream",
40 "Connection": "keep-alive",
41 "Cache-Control": "no-cache"
43 response.writeHead(200, headers);
45 /* Add this new client to our list of clients. */
46 const id = this.add_client(response);
48 /* And queue up cleanup to be triggered on client close. */
49 request.on('close', () => {
50 this.remove_client(id);
56 module.exports = Game;