Storing and retrieving Sockets in Redis
Problem
I am new to Node and Redis, so forgive me if I'm missing something crucial here. I am trying to store a Node.js net.Socket object in Redis, using the node_redis client, so I could reuse a connection made previously on this Socket. I am storing the socket as a Value as a part of a "users" set:
client.sadd("users", username); //username is a string
client.hmset(username, "ip", socket.remoteAddress, "connection", net.Socket(socket));
At a different point, I am retrieving this socket as:
client.smembers("users", function(err, replies) {
replies.forEach(function(reply,i){
if(recipient == reply) { //recipient is the username i've got
client.hget(reply, "connection", function(err, obj) {
console.log("socket's remoteaddress = " + net.Socket(obj).remoteAddress);
net.Socket(obj).write("asdasdasd");
});
}
});
});
But, the: net.Socket(obj).remoteAddress); is logged as 'undefined'. Also, net.Socket(obj).write("asdasdasd"); gives me and error saying:
Error: This socket is closed.
So I guess my question is - can you store Sockets this way in Redis and expect them to work upon retrieval? Is there a correct / better way to do this?
P.S. I tried retrieving the Socket without the cast to net.Socket and it still didn't do any good.
Solution
Sockets and socket APIs (such as Berkeley Sockets) intrinsically handle special system-specific resources for which it just wouldn't make any sense to store or reference on a remote system, or even serialize for that matter.
Although, in reality, sockets are often uniquely identified by file descriptors so you could easily store that small, unique integer in a database for later access; however, that integer would only be meaningful during the active lifetime of that socket within that process instance. A strategy such as this one will be fraught with challenges, mainly having to do with the transient nature of the socket file descriptor number.
Discussion
View additional discussion.