Socket.io websocket authorization failing when clustering node application

后端 未结 1 850
心在旅途
心在旅途 2021-02-04 22:26

Question: Is it possible to cluster an application which is using Socket.io for WebSocket support? If so what would be the best method of implementation?

I\'ve built a

相关标签:
1条回答
  • 2021-02-04 23:06

    What is your sessionStore? If it's the MemoryStore shipped with connect, then sessions won't be shared between your workers. Each worker will have it's own set of sessions, and if a client connects to another worker, you wont find their session. I suggest you take a look at e.g. connect-redis for sharing sessions between processes. Basic usage:

    var connect = require('connect')
      , RedisStore = require('connect-redis')(connect);
    
    var app = connect.createServer();
    app.use(connect.session({store: new RedisStore, secret: 'top secret'});
    

    Of course, this requires that you also set up redis. Over at the Connect wiki there are modules for CouchDB, memcached, postgres and others.

    This only solves part of your problem, though, because now you have sessions shared between workers, but socket.io has no way of sending messages to clients which are connected to other workers. Basically, if you issue a socket.emit in one worker, that message will only be sent to clients connected to that same worker. One solution to this is to use RedisStore for socket.io, which leverages redis to route messages between workers. Basic usage:

    var sio = require('socket.io')
      , RedisStore = sio.RedisStore
      , io = sio.listen(app);
    
    io.set('store', new RedisStore);
    

    Now, all messages should be routed to clients no matter what worker they are connected to.

    See also: Node.js, multi-threading and Socket.io

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