I need to be able to have clients connect using NodeJS Sockets but then be able to send data to specific clients at a later time.
Here is an example about what I am doing now:
var net = require('net');
var sockets = [];
var server = net.createServer(function(c) {
c.sock_id = sockets.push(c);
c.on('close', function() {
delete sockets[c.sock_id];
});
});
server.listen(1234, function() {});
function send_to_socket(id,message) {
sockets[id].write(message);
}
This does not seem to me like the right way to handle this especially in an environment where the sockets are stored in something like Redis.
Can somebody shed some light on the proper way to handle this?
Sockets should have unique identifier. If they are not identified uniquely on connection layer, then you have to create identification your self manually. It can be processId + increment or any other network reliable identification.
Then there is worker that has socket and is responsible for handling its message queue as well as sending messages.
Redis can easily store ID of sockets, but have to store worker ID that this socket is bound as well.
Then you need to have direct communication between workers in order to be able to send messages to each other. This can be done through Redis by having message queues for workers or sockets, and workers responsible for this sockets will pull messages and process them for sending.
Or you can have direct communication from workers to workers for example using ZeroMQ, and send messages directly to them. I would recommend Redis solution for messages. Even if it is one single point of input, but this solution will be more flexible and reliable.
It is better to keep list of sockets as key value object, where key will be id of socket, and value - socket or object with a bit more information and socket it self.
To attach data to socket, you should be able simply add values to socket objects.