Skip to content

Commit

Permalink
Allow more clients to connect, and all of them receive the thingsee d…
Browse files Browse the repository at this point in the history
…evices updates
  • Loading branch information
cvetan5 committed Nov 11, 2015
1 parent 1063082 commit 7a9dfe5
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
var ws = require("nodejs-websocket")
var Hapi = require('hapi');
var apiServer = new Hapi.Server();
var clientList = {};
var clientList = [];

function startWebSocket(port) {
var wsserver = ws.createServer(function(conn) {
conn.on("text", function(str) {
if (str != "ping")
{
console.log('Client registered ' + str);
clientList[str] = conn;
clientList.push(conn);
}
})
});
conn.on("close", function(code, reason) {
for (var property in clientList) {
if (clientList.hasOwnProperty(property)) {
delete clientList[property];
var connId = -1;
for (var i = 0; i < clientList.length; ++i)
{
if (clientList[i] == conn)
{
console.log("Disconnected", i);
connId = i;
break;
}
}
console.log("Connection closed")
})
if (connId != -1)
clientList.splice(connId, 1);
console.log("Connection closed")
});
conn.on("error", function(err) {
console.log("An error occured in WebSocket server:", err);
});
}).listen(port, "127.0.0.1", function() { console.log('WS server running on port: ' + port) });
}

Expand All @@ -42,15 +52,17 @@ function startAPI(settings) {
method: 'POST',
path: settings.apiPath,
handler: function(request, reply) {


var dId = request.headers.deviceauthuuid ? request.headers.deviceauthuuid : 'unknown';
console.log('Received POST data: device ' + dId);
if (clientList.hasOwnProperty(dId)) {
if (clientList.length > 0) {
var response = {};
response.deviceId = dId;
response.data = request.payload;
clientList[dId].sendText( JSON.stringify(response) );
for (var i = 0; i < clientList.length; ++i)
{
console.log("Sending to ", i);
clientList[i].sendText(JSON.stringify(response));
}
}
reply();
}
Expand Down

0 comments on commit 7a9dfe5

Please sign in to comment.