@WebSocketGateway({ cors: true })
export class ChatGateway implements OnGatewayConnection {
@WebSocketServer() server: Server;
handleConnection(client: Socket) {
console.log("connected", client.id);
}
@SubscribeMessage("message")
onMessage(@MessageBody() text: string, @ConnectedSocket() client: Socket) {
this.server.emit("message", { from: client.id, text });
}
}
Create a class with @WebSocketGateway(). Handle the message with @SubscribeMessage(), and broadcast with server.emit().
The gateway. You can pass a port and options like namespace or cors to @WebSocketGateway(). A gateway is a provider. So it goes in a module's providers, and it can inject services. Nest supports socket.io through @nestjs/platform-socket.io, and plain ws through an adapter.
Handling messages:
@SubscribeMessage("message")maps an incoming event to a method.@MessageBody()gives you the payload.@ConnectedSocket()gives you the client's socket.- Returning a value sends an acknowledgement to that client.
Broadcasting. @WebSocketServer() gives you the server instance. server.emit() sends to every connected client.
Extras. OnGatewayInit, OnGatewayConnection and OnGatewayDisconnect add lifecycle hooks. Guards, pipes, interceptors and filters also work. WsException is the error type to throw.
- A gateway is a
@WebSocketGateway()class registered as a provider. @SubscribeMessagehandles events, with@MessageBodyand@ConnectedSocketfor the data and socket.@WebSocketServer()gives the server, which you use to broadcast.- Lifecycle interfaces add hooks for init, connect and disconnect.
- Guards, pipes and filters work, and
WsExceptionis the error type.
Read more
- Gateways (https://docs.nestjs.com/websockets/gateways)docs.nestjs.com