forked from dagumak/lionshare-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebsocketServer.js
64 lines (56 loc) · 1.22 KB
/
WebsocketServer.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
import _ from "lodash";
import uws from "uws";
import Exchange from "./exchange/Exchange";
class WebsocketServer {
constructor(server) {
this.exchange = new Exchange();
this.wss = new uws.Server({
server,
verifyClient: this.verifyClient,
clientTracking: true
});
}
broadcast = data => {
this.wss.clients.forEach(client => {
if (client.readyState === uws.OPEN) {
try {
client.send(data);
} catch (e) {
console.log(e);
}
}
});
};
ping = () => {
this.wss.clients.forEach(client => {
if (client.readyState === uws.OPEN) {
try {
client.ping();
} catch (e) {
console.log(e);
}
}
});
};
verifyClient = info => {
return this.originIsAllowed(info.origin);
};
originIsAllowed = origin => {
// TODO: add origin checks here
return true;
};
start = () => {
this.exchange.connect();
this.exchange.on(
"message",
_.throttle(data => {
this.broadcast(JSON.stringify(data));
}, 1000)
);
setInterval(() => {
// Ping to prevent connections from closing
this.ping();
}, 30000);
};
}
export default WebsocketServer;