Search code examples
node.jswebsocketsocket.iohazelcast

Socket.io with Hazelcast


I have a nodejs application with cluster and I use hazelcast for scalebility. I need to add socket.io for real time messaging but when I connect to the socket on the worker processes, my client's socket object has lost.

I research for a while but I didn't find any solutions. There are too many examples with Redis but I cannot use Redis. I must use Hazelcast.

How can I share the sockets to every process and also every server with Hazelcast? Is there a way?

Node version:v10.16.3

Socket.io version: 2.3.0

Thanks in advance.


Solution

  • Hazelcast provides you both pub/sub mechanism and in-memory caching on a JVM-based Hazelcast cluster and you can connect to cluster via Hazelcast node.js client. So, It gives an ability to manage and scale Socket.io application via pub/sub topics and storing socket ids in a Hazelcast IMap datastructure.

    I can share an example pseudo-code for you:

    /* Assumed multi-instance socket.io servers are working and
    ** they are listening to the Hazelcast pub/sub topics. So, every socket.io
    ** servers can communicate via pub/sub topics and your other applications as well.
    */
    const topic = await client.getTopic('one-of-socket-rooms');
    const map = await client.getMap('user-socket-ids');
    
    io.on('connection', (socket) => {
      console.log('a user connected with socketId: ' + socket.id );
      // assumed you have already userId
      await map.put(userId, socket.id);
      socket.join('one-of-socket-rooms');
      topic.publish('User with '+ socket.id + ' joined the room')
    });
    

    If you can share a specific code piece, I can edit my answer according to your exact requirements.