node.js中的聊天服务器的Redis pub / sub

我正在尝试使用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发布/订阅function,则应该专用一个redis客户端连接来监听某个频道,然后使用第二个redis客户端连接来发送常规命令和/或发布消息到您的频道。 来自node_redis文档:

当客户端发出SUBSCRIBE或PSUBSCRIBE时,该连接将被置于“pub / sub”模式。 此时,只有修改订阅集的命令才有效。 订阅集为空时,连接将恢复正常模式。

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

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

  • Redis / Node.js – 2个客户端(1个pub / sub)导致写入问题
  • 为什么我不能有一个Redis客户端在同一个连接中充当PUB和Sub?

我相信这本书的例子是缺less的东西,我也读了这本书,并感到奇怪。 您订阅了Redis频道,正在等待服务器端的消息,但您从未发布到该频道。 缺less的是一个事件监听器,所以当有一个websocket消息,你发布该消息到redis通道。