-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
104 lines (77 loc) · 2.28 KB
/
client.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
"use strict";
/*!
* WebSocket Realtime Transport - Client
* Copyright(c) 2013 Owen Barnes <[email protected]>
* MIT Licensed
*/
var WebSocket = require('ws');
module.exports = function(options) {
options = options || {};
options.protocol = options.protocol || 'ws';
options.host = options.host || 'localhost';
options.reconnection = options.reconnection || {
attempts: Infinity,
minDelay: 1000,
maxDelay: 8000
};
var attemptReconnect = true;
var reconnectionAttempts = 0;
var reconnecting = false;
function debug() {
var args = Array.prototype.slice.call(arguments);
if (options.debug) console.log.apply(console, args);
}
// Connect
return function (client) {
var ws;
var url = options.protocol + '://' + options.host + ':' + options.port;
function connect(){
debug('Connecting to', url);
ws = new WebSocket(url);
ws.onopen = function() {
return client.status.emit('open');
};
ws.onmessage = function(obj, flags) {
// flags.binary will be set if a binary data is received
// flags.masked will be set if the data was masked
debug('RECV', obj.data);
client.process({message: obj.data});
};
ws.onclose = function() {
client.status.emit('close');
reconnect();
};
}
function reconnect() {
if (!attemptReconnect) return;
// Attempt reconnection
// Note: most of this logic is from socket.io-client at the moment
reconnectionAttempts++;
if (reconnectionAttempts > options.reconnection.attemps) {
client.status.emit('reconnect_failed');
reconnecting = false;
} else {
var delay = reconnectionAttempts * options.reconnection.minDelay;
delay = Math.min(delay, options.reconnection.maxDelay);
debug('Waiting %dms before reconnect attempt', delay);
reconnecting = true;
var timer = setTimeout(function(){
debug('Attempting reconnect...');
connect();
}, delay);
}
}
connect();
// Return API
return {
disconnect: function() {
attemptReconnect = false;
ws.close();
},
write: function(msg) {
debug('SEND', msg);
ws.send(msg);
}
};
};
};