socketio/socket.io-redis-adapter

Error on websocket multi instance using redis-adapter

gaetansenn opened this issue · 1 comments

Hello,

I'm using the socket.io-redis-adapter with nestjs as explained here https://docs.nestjs.com/websockets/adapter to use multi instance of node
I have extended the NestGateway and using the
@WebSocketServer()
server: any;

to get the current server instance and added the method emitToNamespace to emit to the namespace as here

emitToNamespace(namespace: string, channel: string, data?: any) {
    this.server.server._nsps.get(namespace)?.emit(channel, data);
  }

The thing is it's working perfectly when there is only one server but when i'm using load balancer with multiple nest instance the message is not always received.

I have added a console.log inside the emitToNamespace to log the socket and look's like the server that receive the request only see the sockets from the current server as this function only return local server socket and not from the redis :

const socketsMap = this.server.server._nsps.get(namespace)?.sockets;

    if (!socketsMap) return;

    const socketIterator = socketsMap.values();

    for (let i = 0; i < socketsMap.size; i++) {
      const socket = socketIterator.next().value;

      console.log(`namespace ${namespace}/${channel} socket user`, socket.user);
    }

Has anyone know if i'm doing this good is the this.server is provived in a good way and is this going to emit properly and also get the global sockets ?

Thank you 😉

okay my bad I used the methods from socket.io api instance and now it's working

this.server.server.of(namespace);