Node.js中聊天服务器的Redis发布/订阅
我正在尝试使用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发布/订阅功能,则应使用一个Redis客户端连接来监听某个频道,使用另一个Redis客户端连接来发送常规命令和/或将消息发布到您的频道。从node_redis文档:
当客户端发出SUBSCRIBE或PSUBSCRIBE时,该连接将进入“发布/订阅”模式。那时,只有修改订阅集的命令才有效。当订阅集为空时,连接将恢复为常规模式。
如果在发布/订阅模式下需要向Redis发送常规命令,只需打开另一个连接即可。
以上是 Node.js中聊天服务器的Redis发布/订阅 的全部内容, 来源链接: utcz.com/qa/411248.html