Tia*_*bre 11 javascript websocket node.js socket.io node-cluster
我有一个使用集群的服务器,并使用socke.IO工作我正在使用粘性会话,但我的房间有问题(我不知道我的方式是否是最好的选择):集群实例化流程,每个流程都有特定数量的房间.
我将一些用户连接到房间(只有一个进程)的方法是使用路由,用户访问页面,当他尝试与Socket.io建立连接时,我检查URL并使用该信息插入他在一个房间里.
我的问题是使用集群实现此服务器我不能将用户插入特定的房间,因为有些房间只存在于特定的进程中,粘性会话将他放在另一个进程中.如何将用户置于另一个进程中的房间?此外,使用只能查看他在服务器中的进程路由,我想显示页面中的每个房间.
我已经阅读过有关Redis-Adapter的内容,但我没有在使用Socket.io + Cluster(Sticky-session + redis-adapter)+ rooms的github上找到解决方案.
按照我的代码分享我所做的事情:
//Cluster.Master with simplified Code
if (cluster.isMaster) {
var workers = [];
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
}
// Create the outside facing server listening on our port.
var server = net.createServer({
pauseOnConnect: true
}, function(connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var worker = workers[worker_index(connection.remoteAddress, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(process.env.PORT);
} else {
console.log('I am worker #' + cluster.worker.id);
var app = new express();
//view engine
app.set('views', './views');
app.set('view engine', 'pug');
//statics
app.use(express.static(path.join(__dirname, 'public')));
//rooms
app.use('/', rooms);
var server = app.listen(0, 'localhost'),
io = sio(server);
io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
//This File has the socket events (socket.on('messageX', function(){}))
// And there I am
var realtime = require('./realtime/socketIOEvents.js')(io);
// Listen to messages sent from the master. Ignore everything else.
process.on('message', function(message, connection) {
if (message !== 'sticky-session:connection') {
return;
}
// Emulate a connection event on the server by emitting the
// event with the connection the master sent us.
server.emit('connection', connection);
connection.resume();
});
}
Run Code Online (Sandbox Code Playgroud)
socketio-redis 是正确的做法。每个服务器/进程都会监听 Redis 队列中的一个主题。简而言之,socketio-redis 只是将事件发布到集群中的每个其他服务器/进程。因此,就房间而言,它们只是一组有兴趣监听房间中消息的套接字的抽象。
即使套接字分布到不同的服务器/进程,它们也可以是同一房间的一部分。当每条消息进入时,每个服务器都知道它并将其传递到所需的套接字。
就正确性而言,您的架构也是正确的,因为您的代理决定也有选择地转发消息,但它增加了消息生命周期中的跳数。您确实不需要这个代理来处理套接字路由。
| 归档时间: |
|
| 查看次数: |
1000 次 |
| 最近记录: |