-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb-socket-repeater.js
109 lines (88 loc) · 2.68 KB
/
web-socket-repeater.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
var WebSocketServer = require('ws').Server;
var _ = require("underscore");
var util = require('util');
var EventEmitter = require('events').EventEmitter;
/// # WebSocketRepeater
//
// Options:
// * port <Number> only required if no server
// * server <HttpServer>
// * useHeartbeat <Boolean>
function WebSocketRepeater (options) {
var self = this;
if (!options) { options = {}; }
var port = options.port || 8080;
var clientCount = 0;
var idCounter = 0;
this.clients = [];
var wss;
if (options.server) {
wss = new WebSocketServer({server: options.server});
} else {
wss = new WebSocketServer({port: port});
}
// websocket connections
wss.on('connection', function(ws) {
var clientInfo = {
ws: ws,
cid: ++idCounter,
errored: false
};
self.clients.push(clientInfo);
clientCount++;
ws.on('message', function(message) {
self.emit('message', message, ws);
var messageJSON;
var responce;
self.clients.forEach(function (client) {
if (client.cid !== clientInfo.cid) {
client.ws.send(message);
}
});
// try {
// messageJSON = JSON.parse(message);
// } catch (e) {}
// if (messageJSON) {
// testAllRoutes(routes, ws, messageJSON);
// }
});
ws.on('close', function() {
self.clients = _.without(self.clients, clientInfo);
--clientCount;
logClientCount();
});
ws.on('error', function () {
logClientCount();
clientInfo.errored = true;
});
logClientCount();
});
// start the heat beat
if (options.useHeartbeat) {
this.heartbeat();
}
function logClientCount() {
console.log("Client count ", clientCount);
}
}
util.inherits(WebSocketRepeater, EventEmitter);
WebSocketRepeater.prototype.heartbeat = function () {
var self = this;
this.clients.forEach(function (clientInfo) {
if (!clientInfo.errored) {
clientInfo.ws.send('{"resource":"/heartbeat/1000/","body":{"count":"'+this.heartBeatCounter+'"}}');
if (++self.heartBeatCounter > 100000) {
self.heartBeatCounter = 0;
}
}
});
setTimeout(this.heartbeat, this.heartbeatSpeed);
};
WebSocketRepeater.prototype.send = function (message) {
this.clients.forEach(function (clientInfo) {
if (!clientInfo.errored) {
clientInfo.ws.send(message);
}
});
};
module.exports = WebSocketRepeater;