javascript - 带有 socketio : wht doesn't publisher publish message? 的 nodejs 中的 redis pubsub

标签 javascript websocket redis socket.io publish-subscribe

我正在尝试在 nodejs 中使用 redis 和 socketio 发布订阅。

我的服务器端代码是:

var io = require('socket.io').listen(server);
var pub = redis.createClient();

io.sockets.on("connection", function(socket) {
    console.log('connecteed');

    var sub = redis.createClient();

    sub.subscribe("messages");
    sub.on("message", function(channel, message) {
      console.log('message',message);
      socket.emit(channel,message);
    });

    socket.on("disconnect", function() {
      sub.unsubscribe("messages");
      sub.quit();
    });
});
pub.publish("messages", JSON.stringify({type: "foo", content: "bar"}));

我的 html 页面 index.html 包含以下脚本:

var host = window.location.host.split(':')[0];
var socket = io.connect('http://' + host);
socket.on('messages',function(msg){
    console.log(msg);
})

但在 index.html 中 console.log 永远不会执行。

这是基本的,但我没有在我的代码中发现错误。它在哪里?

最佳答案

这可能是因为您在发布消息时没有连接任何客户端(提示 io.socket.on 连接函数在 pub.publish 之后执行)。尝试替换

pub.publish("messages", JSON.stringify({type: "foo", content: "bar"}));

setIntervall(function(){
    pub.publish("messages", JSON.stringify({type: "foo", content: "bar"}));
},1000);

这将每秒发送一次消息,并为您提供充足的时间来验证您的设置。

关于javascript - 带有 socketio : wht doesn't publisher publish message? 的 nodejs 中的 redis pubsub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13631375/

相关文章:

javascript - 初学者 - while 循环中的 document.write

javascript - 将下拉菜单设置为只读

java - 使用tomcat的Eclipse中的WebSocket错误

node.js SPA webapp - 所有通信均通过 websockets

ruby-on-rails - Redis 和 Rails 生产错误:ActionView::Template::Error (ERR invalid DB index)

javascript - jsTestDriver + Nant = 测试目录问题

javascript - PHP 脚本写入本地主机上的文件,但不写入 IIS 服务器上的文件

javax.websocketclient : how to send large binary data from clientendpoint to serverendpoint

redis - redis中的存储和计数

ruby-on-rails - Redis-objects 按模型中的列计算模型实例的数量