-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
90 lines (80 loc) · 2.75 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const app = express();
const appServer = http.createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
appServer.listen(3000, () => {
console.log('Server started on port 3000');
});
const wss = new WebSocket.Server({ noServer: true });
appServer.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, socket => {
wss.emit('connection', socket, request);
});
});
let clientList = new Map();
wss.on('connection', (ws) => {
ws.on('message', (data, isBinary) => {
let request;
try {
request = isBinary ? data : JSON.parse(data.toString());
} catch (e) {
console.log('Received message is not a valid JSON');
return;
}
console.log("Received message: " + request.message);
if (request.message === 'host') {
clientList.set('host', ws);
const response = { id: 'clients', clients: [...clientList.keys()].filter((id) => id !== 'host') };
ws.send(JSON.stringify(response));
ws.send(JSON.stringify({ id: 'system', message: 'Welcome master' }));
console.log(`Host connected`);
} else if (request.message === 'voter') {
const clientId = generateClientId();
clientList.set(clientId, ws);
console.log(`Voter ${clientId} connected`);
ws.send(JSON.stringify({ id: 'welcome', message: `Your client ID: ${clientId}` }));
const host = clientList.get('host');
if (!host) {
console.log('Host not connected');
return;
}
host.send(JSON.stringify({ id: "client-register", clientId }));
} else if (request.message === 'up' || request.message === 'down' || request.message === 'static') {
// Forward valid vote to the host
const clientId = getClientIdByConnection(ws);
console.log(`Received vote from ${clientId}: ${request.message}`);
const host = clientList.get('host');
if (!host) {
console.log('Host not connected');
return;
}
host.send(JSON.stringify({ id: "vote", clientId, message: request.message }));
}
});
ws.on('close', () => {
const clientId = getClientIdByConnection(ws);
const host = clientList.get('host');
if (!host) {
console.log('Host not connected');
return;
}
host.send(JSON.stringify({ id: "client-unregister", clientId }));
console.log(`${clientId} disconnected`);
clientList.delete(clientId);
});
});
function generateClientId() {
return Math.random().toString(36).substring(2, 10);
}
function getClientIdByConnection(ws) {
for (const [clientId, client] of clientList.entries()) {
if (client === ws) {
return clientId;
}
}
return null;
}