2017-08-23 32 views
0

消息特定socket.io客户在我的Express服务器,我使用socket.io和Redis的发布订阅。 服务器预订一个Redis的消息信道,并当有人通过Redis的新发布消息转发Redis的消息发送到特定的WebSocket客户端。前进的Redis PubSub的快递

从我从socket.io和Redis文档中读到的内容,我可以使用变量socket和致电socket.broadcast.to(mySocketID).emit向特定客户端发送消息。

但是,在下面的代码中,如果我想要发送消息给mySocketID内部的redis用户,该用户不在io.on('connection')的范围内,该怎么办?

var redis = require('redis'); 
 
var server = require('http').createServer(app); 
 
var io = require("socket.io")(server); 
 

 
io.on('connection', function (socket) { 
 

 
    socket.on('whatever_event', function() { 
 
     socket.broadcast.to(mySocketID).emit('TEST', 'hello ' + mySocketID); 
 
    } 
 
} 
 

 
var subscriber = redis.createClient(); 
 

 
subscriber.on('message', function (channel, redisMessage) { 
 

 
// I want to send redisMessage to the websocket client 
 
// Can I access to "socket" in io.on('connection' ...) ? 
 

 
});

回答

1

我没有使用WebSockets类似的东西了一段时间后(如果我明白你要做什么)。有效地,我必须创建Redis的发布/订阅(纯醇” EventEmitter)和网页套接字之间的过程中的事件代理层。如果没有这个层,你将会有很多不必要的连接开销,通过使用它你可以限制打开连接到Redis的数量。

因此,subscriber.on部分发送EventEmitter事件(yourEventsObject.emit(/*...*/))。然后你socket.io连接回调里面你响应这些事件与听众(yourEventsObject.on(/*...*/))。当你的socket.io关闭连接,你需要确保和清理这些EventEmitter监听器,这样你就不会得到闭合的插座错误。

这里是full source onarticle describing the problem/solution with websockets完整的文件。