-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwshandle.js
More file actions
64 lines (52 loc) · 1.68 KB
/
Copy pathwshandle.js
File metadata and controls
64 lines (52 loc) · 1.68 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
const {WebSocket} = require('ws');
const log = require('./util/logger.js')('wshandle');
function WebSocketHandle(data = {url, persistent, onOpen, onMessage, onError, onClose, retryTime}) {
this._data = data;
this.create();
return this;
}
WebSocketHandle.prototype.create = function() {
const {url, persistent, onOpen, onMessage, onError, onClose, retryTime} = this._data;
this._ws = new WebSocket(url);
if (onOpen)
this._ws.on('open', () => onOpen.call(this));
if (onMessage) {
this._ws.on('message', data => {
let parsedData = String(data);
try {
parsedData = JSON.parse(parsedData);
} catch (ignored) {}
onMessage.call(this, parsedData);
});
}
if (onError)
this._ws.on('error', e => onError.call(this, e));
this._ws.on('close', (code, reason) => {
if (onClose) onClose.call(this, code, reason);
if (code === 1000) return;
if (persistent) {
log.error(`Connection error to WebSocket ${url}. Retrying in ${retryTime || 3000} ms...`);
setTimeout(() => this.create(), retryTime || 3000);
}
});
}
WebSocketHandle.prototype.send = function(msg) {
if (!this._ws || !msg || this._ws.readyState !== 1) return false;
if (typeof msg === 'object')
msg = JSON.stringify(msg);
if (typeof msg !== 'string')
msg = String(msg);
this._ws.send(msg);
return true;
}
WebSocketHandle.prototype.close = function() {
if (!this._ws) return false;
this._ws.close(1000);
return true;
}
WebSocketHandle.prototype.reload = function(url = null) {
this.close();
if (url) this._data.url = url;
this.create();
}
module.exports = {WebSocketHandle};