Reputation: 2256
How to issue an event to all connected sockets?
export class EventsGateway {
@SubscribeMessage('message')
async onEvent(client, data) {
// The following is the use of `socket.io` to issue events to all connected sockets.
// io.emit('message', data);
}
}
How do I perform this in nestjs?
Upvotes: 5
Views: 10483
Reputation: 2256
NestJS allows you to create message listeners using decorators. Within this method, you are able to respond to the client by returning a WsResponse object.
However, NestJS also allows you to get the WebSocket instance using the WebSocketServer decorator.
To send an Event to all connected clients you will need to use the WebSocketServer
decorator and use the native WebSocket instance to emit a message, like so:
import WebSocketServer from '@nestjs/websockets'
export class EventsGateway {
@WebSocketServer() server;
@SubscribeMessage('message')
onEvent(client: any, payload: any): Observable<WsResponse<any>> | any {
this.server.emit('message', payload);
}
}
Upvotes: 10