1
|
|
|
"use strict"; |
2
|
|
|
|
3
|
1 |
|
const WebSocket = require("ws"); |
4
|
|
|
|
5
|
1 |
|
const handleProtocols = (protocols /*, request */ ) => { |
6
|
|
|
console.info(`Incoming protocol requests '${protocols}'.`); |
7
|
|
|
for (var i = 0; i < protocols.length; i++) { |
8
|
2 |
|
if (protocols[i] === "text") { |
9
|
|
|
return "text"; |
10
|
2 |
|
} else if (protocols[i] === "json") { |
11
|
|
|
return "json"; |
12
|
|
|
} |
13
|
|
|
} |
14
|
|
|
return false; |
15
|
|
|
}; |
16
|
|
|
|
17
|
1 |
|
let makeWss = (server) => { |
18
|
1 |
|
const wss = new WebSocket.Server({ |
19
|
|
|
server: server, |
20
|
|
|
clientTracking: true, // keep track on connected clients |
21
|
|
|
handleProtocols: handleProtocols |
22
|
|
|
}); |
23
|
|
|
|
24
|
1 |
|
return wss; |
25
|
|
|
}; |
26
|
|
|
|
27
|
1 |
|
let broadcastExcept = (wss, ws, data) => { |
28
|
|
|
let clients = 0; |
29
|
|
|
|
30
|
|
|
wss.clients.forEach((client) => { |
31
|
4 |
|
if (client !== ws && client.readyState === WebSocket.OPEN) { |
32
|
|
|
clients++; |
33
|
2 |
|
if (ws.protocol === "json") { |
34
|
|
|
let msg = { |
35
|
|
|
data: data |
36
|
|
|
}; |
37
|
|
|
|
38
|
|
|
client.send(JSON.stringify(msg)); |
39
|
|
|
} else { |
40
|
|
|
client.send(data); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
}); |
44
|
|
|
console.info(`Broadcasted data to ${clients} (${wss.clients.size}) clients.`); |
45
|
|
|
}; |
46
|
|
|
|
47
|
1 |
|
let socket = (server) => { |
48
|
1 |
|
const wss = makeWss(server); |
49
|
|
|
|
50
|
1 |
|
wss.on("connection", (ws /*, req*/ ) => { |
51
|
|
|
console.info("Connection received. Adding client."); |
52
|
|
|
|
53
|
|
|
ws.on("message", (message) => { |
54
|
|
|
console.log(message); |
|
|
|
|
55
|
|
|
broadcastExcept(wss, ws, message); |
56
|
|
|
}); |
57
|
|
|
|
58
|
|
|
ws.on("error", (error) => { |
59
|
|
|
console.error(`Server error: ${error}`); |
60
|
|
|
}); |
61
|
|
|
|
62
|
|
|
ws.on("close", (code, reason) => { |
63
|
|
|
console.info(`Closing connection: ${code} ${reason}`); |
64
|
|
|
}); |
65
|
|
|
}); |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
module.exports = { |
69
|
|
|
socket: socket |
70
|
|
|
}; |
71
|
|
|
|