WS+Nest:服务端和客户端实现

上一篇文章使用 socket.io,但这玩意儿版本兼容性差,API 不稳定,而且维护方可能会跑路。本文简要给出一个使用 WS 库的例子。

服务端:

 1import { WebSocketServer, SubscribeMessage, OnGatewayConnection, OnGatewayDisconnect, WebSocketGateway, MessageBody } from '@nestjs/websockets';
 2import { Server, WebSocket } from 'ws';
 3
 4@WebSocketGateway()
 5export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
 6  @WebSocketServer()
 7  server: Server;
 8
 9  async handleConnection(ws: WebSocket) {
10    console.log('Client connected');
11  }
12  @SubscribeMessage('hello')
13  onEvent(@MessageBody() data: any) {
14    console.log("[Events:hello] data: ", data)
15    return data
16  }
17  async handleDisconnect() {
18    console.log('Client disconnected');
19  }
20}

bootstrap

 1import { NestFactory } from '@nestjs/core';
 2import { AppModule } from './app.module';
 3import { WsAdapter } from '@nestjs/platform-ws';
 4
 5async function bootstrap() {
 6  const app = await NestFactory.create(AppModule);
 7  app.useWebSocketAdapter(new WsAdapter(app));
 8  await app.listen(3000);
 9  console.log(`Application is running on: ${await app.getUrl()}`);
10}
11bootstrap();

客户端:

 1const WebSocket = require('ws');
 2
 3const socket = new WebSocket('ws://localhost:3000');
 4
 5socket.on('open', (client) => {
 6  console.log('Connected to the WebSocket server');
 7  socket.send(JSON.stringify({
 8    event: 'hello',
 9    data: 'Hello from client',
10  }));
11});
12
13socket.on('message', (data) => {
14  console.log('Message from server: ', data.toString());
15});
16
17socket.on('close', () => {
18  console.log('Disconnected from the WebSocket server');
19});
20
21socket.on('error', (error) => {
22  console.error('WebSocket error: ', error);
23});

注意:服务端使用 @SubscribeMessage('hello') 注解的效果相当于在 handleConnection 中手动 on('message') 并解码 JSON。其它的官网都有不废话。