【问题标题】:Redis pub/sub for chat server in node.js用于 node.js 中聊天服务器的 Redis pub/sub
【发布时间】:2011-11-19 19:02:29
【问题描述】:

我正在尝试使用 Redis Cookbook 示例:

var http = require('http'),
io = require('socket.io')
fs = require('fs'),
redis = require('redis'),
rc = redis.createClient(9189, "pike.redistogo.com");
rc.auth("passwd", function() {
    console.log("Connected! to redistogo!");});

rc.on("connect", function() {
    rc.subscribe("chat");
    console.log("rc connect event");
});

我在这里成功了,但从未收到“消息”。

rc.on("message", function (channel, message) {
 console.log("Sending: " + message);
 socketio.sockets.emit('message', message);
});

webpage = http.createServer(function(req, res){
console.log('webpage request starting...');

fs.readFile('./index.htm', function(error, content) {
    if (error) {
        res.writeHead(500);
        res.end();
    }
    else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(content, 'utf-8');
     }
 });
 });

 webpage.listen(7777);

我的客户端 index.htm 是这个

<!docttype html>
<html lang="en">
<head>
    <script src ="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">     </script>
       <script src="http://www.heaphash.com:7777/socket.io/socket.io.js"></script>
       <script>
        var socket = io.connect('www.heaphash.com', { port: 7777});
            socket.on('message', function(data){
               var li = new Element('li').insert(data);
               $('messages').insert({top: li});
           }
        </script>
        <meta charset="utf-8">
        <title>Chat with Redis</title>
 </head>
 <body>
        <ul id="messages">
            <!-- chat messages go here -->
        </ul>
        <form id="chatform" action="">
         <input id="chattext" type="text" value="" />
         <input type="submit" value="Send" />
        </form>
        <script>
                $('#chatform').submit(function(){
                        socket.emit('message', $('chattext').val());
                        $('chattext').val(""); //cleanup the field
                        return false;
                });
        </script>
</body>
</html>

客户端如何发布到特定的 Redis“聊天”频道。

【问题讨论】:

    标签: node.js redis socket.io


    【解决方案1】:

    如果你在你的 node.js 程序中使用 redis pub/sub 功能,你应该使用一个 redis 客户端连接来监听某个频道,第二个 redis 客户端连接用于发送普通命令和/或发布消息到你的频道.来自node_redis docs:

    当客户端发出 SUBSCRIBE 或 PSUBSCRIBE 时,该连接被放置 进入“发布/订阅”模式。此时,只有修改 订阅集有效。当订阅集为空时, 连接恢复到常规模式。

    如果您需要在发布/订阅模式下向 Redis 发送常规命令, 只需打开另一个连接。

    您的问题也与这些问题有关:

    【讨论】:

      【解决方案2】:

      我相信那本书中的例子缺少一些东西,我也读过那本书并想知道。您订阅了 Redis 频道并在服务器端等待消息,但您从未发布到该频道。缺少的是事件侦听器,因此当有 websocket 消息时,您将该消息发布到 redis 通道。

      【讨论】:

        猜你喜欢
        • 2011-08-05
        • 2016-01-18
        • 2012-08-12
        • 1970-01-01
        • 2018-08-16
        • 2020-01-03
        • 2014-11-13
        • 1970-01-01
        • 2016-05-11
        相关资源
        最近更新 更多