我正在构建一个应用程序,服务器偶尔会在给定频道上发布数据:
redisClient.publish('global-channel', data);
客户端需要能够连接到服务器并收听全局广播。这种方法有什么问题吗?具体来说,为每个套接字连接创建一个redisClient?
io.sockets.on('connection', function(socket){
var socketRedis = redis.createClient();
socketRedis.subscribe('global-channel');
socketRedis.on('message', function(ch, msg){
socket.emit('event', msg);
});
});
我是Node,Redis和socket.io的新手......还在学习哪一块应该处理某些任务以及哪里(服务器与客户端) - 谢谢!
答案 0 :(得分:2)
是的,还有更好的方法:
var socketRedis = redis.createClient();
// Subscribe to the channel only one time
socketRedis.subscribe('global-channel');
// Accept any connection you want from socket.io
io.sockets.on('connection', function(socket){
// Do what you want here
});
// Add only one listener to the channel and broadcast
// the message to everyone connect on socket.io
socketRedis.on('message', function(ch, msg){
io.sockets.emit('event', msg);
});