[ ] 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.
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
}
}
I'd like to be able to add event listener directly to the socket instance.
See above example.
I'd like to be able to handle events outside of components and gateways by referencing the socket instance I receive from WebSocketServer.
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"
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.
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 twoWebSocketGateway
components andhandleConnection
fires twice in one. If I remove oneWebSocketGateway
it fires just once.