与node.js,socket.io和redis一对一的聊天应用程序

我目前在node.js和socket.io中有一个聊天应用程序(一对一)。 随着我网站上的用户越来越多,我想在我的聊天应用程序中引入redis。 这是我目前的应用程序的一个小例子:

// all requires and connections io.sockets.on('connection', function(socket) { socket.on('message', function(msg) { // code to get receiverssocket io.sockets.sockets[receiverssocket].emit('message', {"source": msg.sendersusername,"msg": msg.msg}); }); }); 

现在,我正在试图find如何使用redis来做这个例子,但我找不到一个与redis聊天的例子。 我只能find消息发送给所有用户的例子。 这是我看的一个例子

Simple Chat Application Using Redis, Socket.io, and Node.js

我认为这样做的一种方式是为每个用户接收消息创build通道,但这会导致数千个通道。 任何帮助我怎么能做到这一点?

编辑:添加一些代码

 io.sockets.on('connection', function (client) { sub.on("message", function (channel, message) { console.log("message received on server from publish "); client.send(message); }); client.on("message", function (msg) { console.log(msg); if(msg.type == "chat"){ pub.publish("chatting." + msg.tousername,msg.message); } else if(msg.type == "setUsername"){ sub.subscribe("chatting." + msg.user); sub.subscribe("chatting.all" ); pub.publish("chatting.all","A new user in connected:" + msg.user); store.sadd("onlineUsers",msg.user); } }); client.on('disconnect', function () { sub.quit(); pub.publish("chatting.all","User is disconnected :" + client.id); }); }); 

您必须在专用用户频道上发布。 我认为没有别的办法。 但是不要担心,pub / sub频道是不稳定的,所以应该运行良好。

而不是发布到聊天 ,发布您的消息chatting.username ,并订阅两个。

 io.sockets.on('connection', function (client) { sub.subscribe("chatting." + client.id); sub.subscribe("chatting.all" ); sub.on("message", function (channel, message) { console.log("message received on server from publish "); client.send(message); }); client.on("message", function (msg) { console.log(msg); // supose that msg have a iduserto that is the distant contact id if(msg.type == "chat") { pub.publish("chatting." + msg.iduserto,msg.message); } else if(msg.type == "setUsername") { pub.publish("chatting.all","A new user in connected:" + msg.user); store.sadd("onlineUsers",msg.user); } }); client.on('disconnect', function () { sub.quit(); pub.publish("chatting.all","User is disconnected :" + client.id); }); });