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

时间:2014-08-25 09:59:21

标签: node.js sockets redis socket.io node-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});

});

});

现在,我正在尝试使用redis找到如何执行此操作的示例,但我找不到使用redis进行一对一聊天的示例。我只能找到将消息发送给所有用户的示例。这是我看过的一个例子

http://garydengblog.wordpress.com/2013/06/28/simple-chat-application-using-redis-socket-io-and-node-js/

我想到这样做的一种方法是为每个接收消息的用户创建频道,但这会产生数千个频道。关于我如何做到这一点的任何帮助?

编辑:添加了一些代码

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);
});

});

1 个答案:

答案 0 :(得分:2)

您必须在专用用户频道上发布。我认为没有其他办法。但不要担心,发布/订阅频道是不稳定的,因此应该可以正常运行。

不要发布到聊天,而是在 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);
    });
});