Node.js, multi-threading and Socket.io

后端 未结 1 1735
深忆病人
深忆病人 2020-12-04 17:02

I\'m looking to get Socket.io to work multi-threaded with native load balancing (\"cluster\") in Node.js v.0.6.0 and later.

From what I understand, Socket.io uses Re

相关标签:
1条回答
  • 2020-12-04 17:44

    Actually your code should look like this:

    var cluster = require('cluster');
    var http = require('http');
    var numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
      // Fork workers.
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    } else {
      var sio = require('socket.io')
      , RedisStore = sio.RedisStore
      , io = sio.listen(8080, options);
    
      // Somehow pass this information to the workers
      io.set('store', new RedisStore);
    
      // Do the work here
      io.sockets.on('connection', function (socket) {
        socket.on('chat', function (data) {
          socket.broadcast.emit('chat', data);
        })
      });
    }
    

    Another option is to open Socket.IO to listen on multiple ports and have something like HAProxy load-balance stuff. Anyway you know the most important thing: using RedisStore to scale outside a process!

    Resources:

    http://nodejs.org/docs/latest/api/cluster.html
    How can I scale socket.io?
    How to reuse redis connection in socket.io?
    Node: Scale socket.io / nowjs - scale across different instances
    http://delicious.com/alessioaw/socket.io

    0 讨论(0)
提交回复
热议问题