Nest: WebSocketServer .on not firing but SubscribeMessage working

Created on 1 May 2018  路  3Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When trying to catch events through WebSocketServer reference like the below setup, no events are fired but the SubscribeMessage does work on the same event. Emits however do work from the WebSocketServer instance.

@WebSocketGateway()
export class MyGateway implements OnGatewayInit {

  @WebSocketServer() server: SocketIO.Server;

  afterInit() {
    this.server.on('my:event', (data) => {
      console.log('my:event triggered by adding listener to socket'); // doesn't work
    });
  }

  @SubscribeMessage('my:event')
  async onMyEvent(client: any, data: any): Promise<WsResponse<any>> {
    console.log('my:event triggered by subscribing');   // works
  }

}

Expected behavior

I'd like to be able to add event listener directly to the socket instance.

Minimal reproduction of the problem with instructions

See above example.

What is the motivation / use case for changing the behavior?

I'd like to be able to handle events outside of components and gateways by referencing the socket instance I receive from WebSocketServer.

Environment


Nest version:
"@nestjs/common": "^4.5.9",
"@nestjs/core": "^4.5.10",
"@nestjs/microservices": "^4.5.8",
"@nestjs/testing": "^4.5.5",
"@nestjs/websockets": "^4.5.8"

Most helpful comment

Thanks for the fast response!

Is it expected behaviour that the handleConnection gets fired as many times as there are gateways? I have two WebSocketGateway components and handleConnection fires twice in one. If I remove one WebSocketGateway it fires just once.

All 3 comments

Hi @FranciZ,
Use OnGatewayConnection instead:

handleConnection(socket) {
  socket.on('my:event', (data) => {
      console.log('my:event triggered by adding listener to socket'); 
  });
}

Thanks for the fast response!

Is it expected behaviour that the handleConnection gets fired as many times as there are gateways? I have two WebSocketGateway components and handleConnection fires twice in one. If I remove one WebSocketGateway it fires just once.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings