forked from phoboslab/jsmpeg
-
Notifications
You must be signed in to change notification settings - Fork 1
/
module-wsClient.js
51 lines (40 loc) · 1.03 KB
/
module-wsClient.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
const WebSocket = require('ws');
function wsClient(url, interval, recv)
{
var WSClient = function() {
this.url = url;
this.interval = interval;
this.reconnectTimeoutId = 0;
this.recv = recv;
};
WSClient.prototype.start = function() {
this.socket = new WebSocket(this.url, {
perMessageDeflate: false
});
this.socket.binaryType = 'nodebuffer';
this.socket.on('message', function incoming(data) {
this.recv(data);
}.bind(this));
this.socket.on('open', function open(){
this.recv(null);
}.bind(this));
this.socket.on('error', this.onClose.bind(this));
this.socket.on('close', this.onClose.bind(this));
return this;
};
WSClient.prototype.onClose = function(ev) {
clearTimeout(this.reconnectTimeoutId);
this.reconnectTimeoutId = setTimeout(function(){
this.start();
}.bind(this), this.interval);
};
WSClient.prototype.send = function(data) {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(data);
}
};
return new WSClient().start();
}
module.exports = {
wsClient
};