gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:25:55 29 4
gpt4 key购买 nike

我正在尝试使用 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“聊天” channel 。

最佳答案

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

When a client issues a SUBSCRIBE or PSUBSCRIBE, that connection is put into "pub/sub" mode. At that point, only commands that modify the subscription set are valid. When the subscription set is empty, the connection is put back into regular mode.

If you need to send regular commands to Redis while in pub/sub mode, just open another connection.

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

关于node.js - 用于 node.js 中聊天服务器的 Redis pub/sub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463714/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com