+function handle_events(request, response) {
+ /* These headers will keep the connection open so we can stream events. */
+ const headers = {
+ "Content-type": "text/event-stream",
+ "Connection": "keep-alive",
+ "Cache-Control": "no-cache"
+ };
+ response.writeHead(200, headers);
+
+ /* Now that a client has connected, first we need to stream all of
+ * the existing players (if any). */
+ if (game._players.length > 0) {
+ const players_json = JSON.stringify(game.players);
+ const players_data = `event: players\ndata: ${players_json}\n\n`;
+ response.write(players_data);
+ }
+
+ /* Add this new client to our list of clients. */
+ const id = game.add_client(response);
+
+ /* And queue up cleanup to be tirggered on client close. */
+ request.on('close', () => {
+ game.remove_client(id);
+ });
+}
+