Search code examples
node.jssocketstcpwebsocketnestjs

Using multiple sockets adapters with NestJS


I'm working on an Node.js application with NestJS. I need to communicate with 2 other apps.

The first one over WebSockets (Socket.io) and the other one over TCP sockets with net module.

Is it possible to use two gateways with specific adapters, one based on Socket.io and the other one on Net module, or do I have to split this application?


Solution

  • You don't need to split the application.

    You can define your module as:

    @Module({
      providers: [
        MyGateway,
        MyService,
      ],
    })
    export class MyModule {}
    

    with the gateway being in charge of the web sockets channel

    import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'
    import { Socket } from 'socket.io'
    ...
    @WebSocketGateway()
    export class MyGateway {
      constructor(private readonly myService: MyService) {}
    
      @SubscribeMessage('MY_MESSAGE')
      public async sendMessage(socket: Socket, data: IData): Promise<IData> {
        socket.emit(...)
      }
    }
    

    and the service being in charge of the TCP channel

    import { Client, ClientProxy, Transport } from '@nestjs/microservices'
    ...
    @Injectable()
    export class MyService {
      @Client({
        options: { host: 'MY_HOST', port: MY_PORT },
        transport: Transport.TCP,
      })
      private client: ClientProxy
    
      public async myFunction(): Promise<IData> {
        return this.client
          .send<IData>({ cmd: 'MY_MESSAGE' })
          .toPromise()
          .catch(error => {
            throw new HttpException(error, error.status)
          })
      }
    }