-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bus.js
72 lines (59 loc) · 1.98 KB
/
Bus.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
/*
* This file is part of the Muze Server-sent eventbus
*
* (c) Muze <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require('./SSEConnection.js');
Bus = function(id,password) {
var clients = {};
this.id = id;
this.messageId = '1';
this.password = password;
console.log('bus with password: \'' + this.password + '\' created');
//adds a new connection to the clientlist
this.addConnection = function(request,response){
var uniqueId = this.socketUniqueIdentifier(request.connection);
var connection = new SSEConnection(request,response);
var onCloseHandler = function(){
delete clients[uniqueId];
console.log('client deleted with identifier: ' + uniqueId);
};
console.log('client added with identifier: '+ uniqueId);
connection.request.connection.addListener('close',onCloseHandler);
clients[uniqueId] = connection;
};
//writes to all connected sockets on the bus
this.writeToAllSockets = function (data){
console.log('writing data: ' + decodeURIComponent(data));
var dataArray = [];
//check if the data was split up in multiple parts
if(data.indexOf('%0D%0A')){
dataArray = data.split('%0D%0A');
} else {
dataArray.push(data);
}
//add a newline to every line
for(var dataKey in dataArray){
dataArray[dataKey] += '\n';
}
//add a second newline to the last line
dataArray[dataArray.length-1] += '\n';
for(var key in clients){
clients[key].writeOut(this.messageId,dataArray);
}
this.messageId++;
};
//returns an identifier based on the socket,
//a concatination of the localaddress, port, remote address and that port.
this.socketUniqueIdentifier = function(socket){
var localAddress = socket.address().address;
var localPort = socket.address().port;
var remoteAddress = socket.remoteAddress;
var remotePort = socket.remotePort;
return localAddress + '-' + localPort + '-' + remoteAddress + '-' + remotePort;
};
return this;
};