Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io+redis+expressjs cluster - get socket object in expressjs request

Question based on this answer: https://stackoverflow.com/a/18650183/4478897

I tried to find this solution but nothing seems to work in the way that I need.

Clustering expressjs and socket.io we can share sessions using redis and send io messages inside io world (io.sockets.on('connection',...). The problem is if we want to send the message (or use a simple socket.join/leave) inside the expressjs world (route.get/post).

If we are not using clusters we can atach the client socket object to the express request object (or simply export the io object) and then use it at any time on any GET/POST route.

At the other hand, if we are clustering and use the mentioned method to get the socket object inside the expressjs world, sometimes the socket object is undefined because the socket object for this client is initialized at other worker.

Some example flow:

  • Client connects to http://localhost and worker 1 handles this request.
  • After the page is loaded, the client connects to socket.io. Worker 2 handles this connection.
  • Client do a POST and again worker 1 or worker X handles this request.

In this case when the client do the POST, only the worker 2 knows the socket object for this client. So this will get an undefined socket object.

So, the question:

How can we get the client socket object from any worker to reuse it on expressjs request object.

Maybe my code is wrong but is almost like the link to the answer mentioned above.


NOTEs

  • Don't want to use some kind of proxy.
  • Don't want to migrate to other libraries (expressio, sockjs...)
  • Sorry for my English :)

Using last nodejs, socket.io, expressjs, socket.io-redis, redis... versions

Don't hesitate to ask something!


UPDATE 1

Possible solution but still need to test it. Dont know if this is a really good: solution.

  • UPDATE 3: Working code on my own answer

UPDATE 2

Like update 1 but using https://nodejs.org/dist/latest-v5.x/docs/api/cluster.html#cluster_event_message

like image 742
nada Avatar asked Nov 21 '22 15:11

nada


1 Answers

remoteJoin and remoteLeave methods were added in socket.io-redis 3.0.0:

io.adapter.remoteJoin('<my-id>', 'room1', function (err) {
  if (err) { /* unknown id */ }
  // success
});

io.adapter.remoteLeave('<my-id>', 'room1', function (err) {
  if (err) { /* unknown id */ }
  // success
});

Note: The implementation looks a lot (hopefully?) like the answer above.

like image 120
darrachequesne Avatar answered Nov 23 '22 16:11

darrachequesne