如何向所有连接的套接字发出事件?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我如何在nestjs中执行此操作?
NestJS 允许您使用装饰器创建消息侦听器。在此方法中,您可以通过返回WsResponse对象来响应客户端。
但是,NestJS 还允许您使用WebSocketServer装饰器获取 WebSocket 实例。
要将事件发送到所有连接的客户端,您需要使用WebSocketServer装饰器并使用本机 WebSocket 实例来发出消息,如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8756 次 |
| 最近记录: |