我正在使用多个聊天服务器(nodeJS)和一个Redis服务器制作聊天应用程序,这应该有助于对所有nodeJS实例进行分组。好吧,我有这个:
var io = require('socket.io').listen(3000);
// Create a Redis client
var redis = require('redis');
client = redis.createClient(6379, '54.154.149.***', {});
// Check if redis is running
var redisIsReady = false;
client.on('error', function(err) {
redisIsReady = false;
console.log('redis is not running');
console.log(err);
});
client.on('ready', function() {
redisIsReady = true;
console.log('redis is running');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data){
client.set('user:' + data, socket.id);
})
socket.on('send message', function(data){
client.get('user:' + data['id'], function (err, socketId) {
io.sockets.connected[socketId].emit('new message',data['msg']);
});
})
socket.on('disconnect', function(data){
});
});
Redis运行正常,如果我在同一服务器上有两个用户,他们可以聊天。但是,如果它们位于不同的服务器上,则不能,因为套接字不在服务器之间共享。我该如何解决?我检查了关于redis上的pub/sub的信息,我敢肯定这是答案,但我没有设法实现它。
最佳答案
Socket.IO文档包含有关doing sticky sessions and distributing messages的部分。不过,快速的答案是使用类似 socket.io-redis
的模块。
关于node.js - 通过单独的nodeJS实例共享套接字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28050539/