-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathws-server.js
More file actions
76 lines (65 loc) · 2.26 KB
/
ws-server.js
File metadata and controls
76 lines (65 loc) · 2.26 KB
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
const WebSocketServer = require('ws').Server;
const uuid = require('uuid');
class WSServer {
constructor() {
this.connectionInfoMap = {};
}
send(data, socketInfo) {
if (socketInfo.send) {
socket.send(JSON.stringify(data));
} else {
socketInfo.socket.send(JSON.stringify(data));
}
}
sendToList(data, socketInfoList) {
socketInfoList.forEach(s => this.send(data, s));
}
sendAll(data) {
this.sendToList(data, Object.values(this.connectionInfoMap));
}
init(options) {
this.server = new WebSocketServer(options);
this.server.on("connection", (socket, req) => {
socket.id = uuid.v4();
let info = {};
info.socket = socket;
info.req = req;
this.connectionInfoMap[socket.id] = info;
let address = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log('WebSocket Connection Start:', address);
socket.on("message", (message) => {
let data;
try {
data = JSON.parse(message);
} catch (e) {
console.error('Error JSON Parsing:', message.length, message);
}
if (this.handler) {
try {
this.handler(data, info);
} catch (e) {
console.error('WSHandling Error!');
console.error(e);
console.error(data);
}
}
});
socket.on("error", (error) => {
console.error(`WebSocketError${address}: ${error}`);
if (this.errorHandler) {
info.error = error;
this.errorHandler(info);
}
socket.close();
});
socket.on("close", () => {
console.error(`WebSocket Connection Close: ${address}`);
delete this.connectionInfoMap[info.socket.id];
if (this.closeHandler) {
this.closeHandler(info);
}
});
});
}
}
exports = module.exports = new WSServer();