-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReconnectingSocket.js
130 lines (109 loc) · 3.79 KB
/
ReconnectingSocket.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// "author": "Samuel Reed <[email protected]> (http://strml.net/)",
// "license": "MIT",
// from https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs
'use strict';
const WebSocket = require('ws');
function WebSocketClient(){
this.autoReconnectInterval = 1000; // ms
this.logConnection = true;
}
WebSocketClient.prototype.open = function(url){
this.url = url;
this.instance = new WebSocket(this.url);
this.instance.on('open', (function() {
this.log("Connected.");
this.onopen();
}).bind(this));
this.instance.on('message', (function(data, flags) {
this.onmessage(data,flags);
}).bind(this));
this.instance.on('close', (function(code) {
let reconnecting = false;
switch (code){
case 1000: // CLOSE_NORMAL
//console.log("WebSocketClient on close: Closed");
break;
case 1011: // UNEXPECTED_CONDITION
this.logError("Closing Websocket")
break;
default: // Abnormal closure
this.logError('Websocket closed.');
reconnecting = true;
break;
}
this.onclose(code);
if (reconnecting) {
this.reconnect(code);
} else {
this.onend(code);
}
}).bind(this));
this.instance.on('error', (function(e) {
if (e.code) {
this.logError("Error on connection.", e.message);
}
switch (e.code){
case 'ECONNREFUSED':
break;
default:
this.onerror(e);
break;
}
}).bind(this));
this.instance.on('unexpected-response', (function(request, response) {
// Parse body
let buf = '';
response.on('data', function(data) { buf += data; });
response.on('end', (function () {
if (response.statusCode === 401) {
this.logError('Authentication invalid. Please check your credentials. Message: '+buf);
} else {
this.logError('Unexpected response from server ['+response.statusCode+']: '+buf);
}
this.log('The WebSocket will terminate. Please manually reconnect.');
request.abort();
this.instance.close(1011);
this.instance.emit('close', 1011);
}).bind(this))
}).bind(this))
};
// Forward eventemitter methods
['on', 'off', 'once', 'addListener', 'removeListener', 'emit', 'close'].forEach(function(key) {
WebSocketClient.prototype[key] = function() {
this.instance[key].apply(this.instance, arguments);
};
});
WebSocketClient.prototype.log = function() {
if (!this.logConnection) return;
const args = [].slice.call(arguments);
console.log.apply(console, ['WebSocket [INFO]:'].concat(args));
}
WebSocketClient.prototype.logError = function() {
const args = [].slice.call(arguments);
console.error.apply(console, ['WebSocket [ERROR]:'].concat(args));
}
WebSocketClient.prototype.send = function(data, option) {
try{
//console.log(data);
this.instance.send(data, option);
} catch (e){
this.instance.emit('error',e);
}
};
WebSocketClient.prototype.reconnect = function(_code) {
this.emit('reconnect');
this.log('Retry in ' + this.autoReconnectInterval + ' ms');
clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = setTimeout( (function() {
this.instance.close(1000, 'Reconnecting.');
this.log("Reconnecting...");
this.open(this.url);
}).bind(this), this.autoReconnectInterval);
};
WebSocketClient.prototype.reconnect_now = function(_code) {
this.emit('reconnect');
this.instance.close(1000, 'Reconnecting.');
this.log("Reconnecting...");
this.open(this.url);
};
module.exports = WebSocketClient;