2011-09-18 22 views
9

私はRedisのクックブックの例を仕事にしようとしている:チャットサーバーのRedisのパブ/サブに

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は、クライアントが特定のRedisの "チャット" チャンネルに公開しないか、この

<!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> 

です。

答えて

7

node.jsプログラム内でredis pub/sub機能を使用している場合は、通常のコマンドを送信したり、チャンネルにメッセージを公開するためのredisクライアント接続を、 )。 node_redisドキュメントから:

クライアントはSUBSCRIBEまたはPSUBSCRIBE発行

は、その接続は、「パブリッシュ/サブスクライブ」モードに を入れています。その時点で、サブスクリプション・セット を変更するコマンドだけが有効です。サブスクリプション・セットが空の場合、 接続は通常モードに戻されます。

pub/subモードでRedisに定期的なコマンドを送信する必要がある場合は、 は別の接続を開くだけです。

あなたの問題はまた、これらの質問に関連している:

1

私はその本からの例では、何かが欠けていることを信じて、私もその本を読んで疑問に思った。あなたはRedisチャンネルに加入しており、サーバー側のメッセージを待っていますが、決してそのチャンネルには公開しません。欠けているのはイベントリスナーなので、websocketメッセージがあるときは、そのメッセージをredisチャネルにパブリッシュします。

関連する問題