Socket.io websocket authorization failing when clustering node application

两盒软妹~` 提交于 2019-12-03 00:49:54
Linus Gustav Larsson Thiel

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!