我有2个运行socket.io的快速服务器,并使用Redis存储socketID。我有一个设备1连接到快递服务器1,另一个设备2连接到快递服务器2。当我尝试从设备1向设备2发送消息时,我注意到socket.io服务器确实选择了正确的套接字ID,但另一个设备却没有似乎收到消息
我不确定使用多个节点时如何发送消息。这是下面的代码:
var socketIO = require('socket.io');
var io = socketIO(server);
var client;
// Create a Redis client
const redisPort = redisConfig.redisPort,
redisHostname = redisConfig.redisHost,
var redis = require('redis');
var RedisStore = require('socket.io-redis');
var adapter = RedisStore({ host: redisHostname, redisPort });
io.adapter(adapter);
client = adapter.pubClient;
// When a client connects
io.sockets.on('connection', function (socket) {
// Log in a user with their provided username
socket.on('login', function (data) {
var timerCount = 0;
var login = function () {
client.get('user:' + data.rec, function (err, socketId) {
try {
io.to(socketId).emit('message', data);
} catch (err) {
if (timerCount === 100) {
console.log("Waiting for user to join chat timed out!");
}
// Cant find user - user has not joined yet
console.log(err);
timerCount++;
setTimeout(login, 2000);
}
});
}
├─┬ socket.io@2.0.4
│ ├── socket.io-adapter@1.1.1
│ ├─┬ socket.io-client@2.0.4
│ │ ├── socket.io-parser@3.1.2 deduped
│ └─┬ socket.io-parser@3.1.2
├─┬ socket.io-redis@5.2.0
│ ├── socket.io-adapter@1.1.1 deduped