Imagine a web socket server. When I receive a connection I need to save that connection in the pool it belongs to (think about the pool as a "room" of "peers"). This is needed because I need to broadcast stuff to the peers of the same pool.
The code is - of course - all asynchronous and even if Node is single threaded, it seems that maintaining a global array is not reliable (I'm not sure how this is possible, though...): during a stress test, with messages flowing very fast to the server, I save the connection in the structure but often the next messages don't find that structure (still?) updated, behaving erratically.
The application uses Redis, but the socket cannot be serialized...
Communication is based on WebSockets, via SockJS (I used Socket.io in a previous iteration).
I'm sure this is a well known and already solved problem, but I still don't see the light: what am I'm missing here?
My Sessions object is more or less something like that (more than a pseudocode... it's a lot more complicated than that).
var Sessions = {
sockets: {},
add: function(poolId, socket) {
sockets[poolId].push(socket);
},
find: function(poolId) {
return sockets[poolId];
},
remove: function ...
}
I'm not sure I understand what the exact problem you're having is, but here is an example of a server that maintains a pool of sockets. Once connected a socket can send messages that only get broadcast to their assigned pool, which is what I believe you're trying to accomplish. Also when the client disconnects it removes its self from the pool.
var net = require('net');
var util = require('util');
var currentPool = 1;
var server = net.createServer();
//add a new socket to the assigned pool stored on the listening server instance
server.addToPool = function(s){
if(!server.connPools){
server.connPools = {};
}
if(!server.connPools[s.poolId]){
server.connPools[s.poolId] = [];
}
server.connPools[s.poolId].push(s);
s.on('close', clientCloseHandler);
s.on('data', clientDataHandler);
};
//broadcast data from client to other clients in their pool
function clientDataHandler(data){
for(var a=0; a < server.connPools[this.poolId].length; a++){
server.connPools[this.poolId][a].write(data);
}
}
//remove client form pool on disconnect
function clientCloseHandler(){
var tmp = null;
for(var a=0; a < server.connPools[this.poolId].length; a++){
if(this.remotePort === a.remotePort){
tmp = a;
break;
}
}
server.connPools[this.poolId].splice(tmp,1);
}
//add new client to pool
function newClient(s){
s.poolId = currentPool;
server.addToPool(s);
if(currentPool === 1){
currentPool = 2;
}else{
currentPool = 1
}
}
server.on('connection', newClient);
server.listen(9999);