-
Notifications
You must be signed in to change notification settings - Fork 0
/
app-ws.js
41 lines (30 loc) · 1014 Bytes
/
app-ws.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
const { handle } = require('express/lib/application');
const WebSocket = require('ws');
module.exports = (server, handler) => {
const wss = new WebSocket.Server({
server
});
wss.getUniqueID = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4();
};
wss.on('connection', (ws, req) => {
ws.id = wss.getUniqueID();
ws.on('message', data => {
console.log(`onMessage (${ws.id}): ${data}`);
const msg = JSON.parse(data);
handler.handleMsg(wss, ws, msg);
});
ws.on("close", function () {
handler.handleExit(wss, ws);
});
ws.on('error', error => {
console.error(`onError: ${err.message}`);
});
console.log(`onConnection ` + ws.id);
});
console.log(`App Web Socket Server is running!`);
return wss;
}