-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.js
46 lines (35 loc) · 993 Bytes
/
websocket.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
const WebSocket = require('ws');
const pako = require('pako');
exports.init = function init(url, subscribe, handler) {
const ws = new WebSocket(url);
const wsStore = { ws, closed: false };
ws.on('open', () => {
console.log('socket open');
subscribe(ws);
});
ws.on('message', data => {
const text = pako.inflate(data, { to: 'string' });
const message = JSON.parse(text);
if (message.ping) {
try {
ws.send(JSON.stringify({ pong: message.ping }));
} catch (error) {
console.log(`socket send error: ${error}`);
}
} else if (message.tick) {
handler(message);
} else {
console.log(`socket message: ${JSON.stringify(message)}`);
}
});
ws.on('error', error => {
console.log(`socket error: ${error}`);
init(url, subscribe, handler);
});
ws.on('close', () => {
console.log('socket close');
if (wsStore.closed) return;
init(url, subscribe, handler);
});
return wsStore;
};