2011-09-18 57 views
9

我努力工作Redis的食譜例如:的Redis的pub/sub

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的 「聊天」 的頻道。

回答

7

如果您在node.js程序中使用redis發佈/訂閱功能,您應該專用一個redis客戶端連接來監聽某個頻道和第二個redis客戶端連接,以便發送常規命令和/或發佈消息到您的頻道)。從node_redis文檔:

當一個客戶端發出認購或PSUBSCRIBE,該連接把 到「發佈/訂閱」模式。此時,只有修改 訂閱集的命令纔有效。當訂閱集爲空時, 連接將恢復到常規模式。

如果您需要在發佈/訂閱模式下向Redis發送常規命令,則只需打開另一個連接。

您的問題,也涉及到這些問題:

1

我認爲,從書中的例子是失去了一些東西,我也讀過那本書和想知道。您訂閱了Redis頻道並正在等待服務器端的消息,但您從未發佈到該頻道。缺少的是一個事件監聽器,所以當有一個websocket消息時,你將該消息發佈到redis通道。