Reputation: 43
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.
Upvotes: 4
Views: 5464
Reputation: 215
as @maerics said , redis store only string. so your socket data will be destroyed and will give undefined as answer.
you can store your socket like this.
var OBJECT = Object.prototype;
OBJECT.rhash = {};
OBJECT.rset = function(id, object) {
OBJECT.rhash[id] = object;
return id;
};
OBJECT.rget = function(id) {
return OBJECT.rhash[id];
};
this will store reference to that object and reuse it again..
var id = OBJECT.rset("a123",socket);
var ref = OBJECT.rget("a123");
console.log(ref.remoteAddress);
Upvotes: 3
Reputation: 10015
Regarding the IP address, it's on a different hash key (not connection
, but ip
). So to get the value you just read from that key:
client.hget(reply, "ip", function(err, obj) {
console.log("socket's remoteaddress = " + obj);
});
Upvotes: 0
Reputation: 156662
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.
Upvotes: 3