forked from AtOmXpLuS/bitfinex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.js
80 lines (69 loc) · 2.02 KB
/
socket.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const WebSocket = require('ws')
const bitfinex = require('./models/bitfinex');
const message = require('./models/message');
function WebSocketClient() {
this.number = 0;
this.autoReconnectInterval = 5 * 1000;
}
WebSocketClient.prototype.open = function (url) {
this.url = url;
this.instance = new WebSocket(this.url);
this.instance.on('open', () => {
this.onopen();
});
this.instance.on('message', (data, flags) => {
this.number++;
this.onmessage(data, flags, this.number);
});
this.instance.on('close', (e) => {
switch (e) {
case 1000:
console.log("WebSocket: closed");
break;
default:
this.reconnect(e);
break;
}
this.onclose(e);
});
this.instance.on('error', (e) => {
switch (e.code) {
case 'ECONNREFUSED':
this.reconnect(e);
break;
default:
this.onerror(e);
break;
}
});
}
WebSocketClient.prototype.send = function (data, option) {
try {
this.instance.send(data, option);
} catch (e) {
this.instance.emit('error', e);
}
}
WebSocketClient.prototype.reconnect = function (e) {
console.log(`WebSocketClient: retry in ${this.autoReconnectInterval}ms`, e);
this.instance.removeAllListeners();
var that = this;
setTimeout(function () {
console.log("WebSocketClient: reconnecting...");
that.open(that.url);
}, this.autoReconnectInterval);
}
WebSocketClient.prototype.onopen = function (e) {
bitfinex.socketAuth(this);
}
WebSocketClient.prototype.onmessage = function (data, flags, number) {
message.parse( data, this );
}
WebSocketClient.prototype.onerror = function (e) {
console.log("WebSocketClient: error", arguments);
}
WebSocketClient.prototype.onclose = function (e) {
console.log("WebSocketClient: closed", arguments);
}
var wsc = new WebSocketClient();
wsc.open(bitfinex.wssUrl);