在Nestjs中实现实时通信功能时,如何正确配置WebSocket或Socket.IO模块?

在Nestjs中实现实时通信功能时,如何正确配置WebSocket或Socket.IO模块?官方文档提到的Gateway装饰器具体有哪些使用注意事项?

遇到客户端频繁断开重连的情况,该从哪些方面排查问题(如心跳机制、CORS配置或Nginx代理设置)?

能否分享一个结合Redis适配器实现多节点广播的完整示例?包括前端(Vue/React)连接的最佳实践和常见错误处理方案。

与传统HTTP接口相比,实时通信的性能监控和日志记录有哪些需要特别关注的要点?

3 回复

在Nestjs中实现实时通信可以借助Socket.IO库。首先安装依赖:npm install @nestjs/websockets socket.io. 创建一个WebSocketGateway:

// src/gateway.gateway.ts
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway()
export class Gateway {
  @WebSocketServer() server: Server;

  handleConnection(client: Socket) {
    console.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }

  sendMessage(message: string) {
    this.server.emit('message', message);
  }
}

然后在模块中注册它:

// src/app.module.ts
import { Module } from '@nestjs/common';
import { Gateway } from './gateway.gateway';

@Module({
  providers: [Gateway],
})
export class AppModule {}

启动应用后,客户端可通过io('http://localhost:3000')连接,并监听’message’事件接收消息。这是一个简单的示例,实际项目可能需要更复杂的权限管理、频道划分等。


首先安装 Nestjs 项目:npm i -g [@nestjs](/user/nestjs)/cli,然后创建项目 nest new realtime-chat

  1. 安装依赖:

    npm install --save [@nestjs](/user/nestjs)/websockets socket.io [@nestjs](/user/nestjs)/platform-socket.io
    
  2. 创建 WebSocket 模块:nest generate module chat

  3. 创建聊天服务:nest generate service chat/chat,编辑 chat.service.ts 实现消息处理逻辑。

  4. 创建聊天控制器:nest generate controller chat,编辑 chat.controller.ts 绑定路由和事件:

    import { OnGatewayConnection, OnGatewayDisconnect } from '[@nestjs](/user/nestjs)/websockets';
    import { Server, Socket } from 'socket.io';
    
    [@WebSocketController](/user/WebSocketController)()
    export class ChatController implements OnGatewayConnection, OnGatewayDisconnect {
      handleConnection(client: Socket) {
        console.log(`Client connected: ${client.id}`);
      }
    
      handleDisconnect(client: Socket) {
        console.log(`Client disconnected: ${client.id}`);
      }
    }
    
  5. 配置 AppModule 引入 WebSocket:

    [@Module](/user/Module)({
      imports: [
        ChatModule,
        NestWebSocketModule.forRoot({
          cors: true,
        }),
      ],
    })
    export class AppModule {}
    
  6. 运行项目:npm run start:dev,客户端通过 ws://localhost:3000 访问。

NestJS构建实时通信功能教程

1. 安装必要依赖

首先安装WebSocket相关依赖:

npm install @nestjs/websockets @nestjs/platform-socket.io socket.io

2. 创建WebSocket网关

// src/chat/chat.gateway.ts
import { SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class ChatGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: string): void {
    this.server.emit('message', payload); // 广播消息给所有客户端
  }

  afterInit(server: Server) {
    console.log('WebSocket Gateway initialized');
  }

  handleConnection(client: Socket) {
    console.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }
}

3. 注册Gateway模块

// src/chat/chat.module.ts
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';

@Module({
  providers: [ChatGateway],
})
export class ChatModule {}

4. 在AppModule中导入

// src/app.module.ts
import { Module } from '@nestjs/common';
import { ChatModule } from './chat/chat.module';

@Module({
  imports: [ChatModule],
})
export class AppModule {}

5. 客户端连接示例

// 前端代码示例
const socket = io('http://localhost:3000');

// 发送消息
socket.emit('message', 'Hello World!');

// 接收消息
socket.on('message', (msg) => {
  console.log('Received message:', msg);
});

进阶功能

  1. 房间功能
@SubscribeMessage('joinRoom')
handleJoinRoom(client: Socket, room: string) {
  client.join(room);
  client.emit('joinedRoom', room);
}

@SubscribeMessage('messageToRoom')
handleMessageToRoom(client: Socket, data: { room: string; message: string }) {
  this.server.to(data.room).emit('message', data.message);
}
  1. 用户认证
@WebSocketGateway({
  cors: {
    origin: '*',
  },
  namespace: 'chat',
  transports: ['websocket'],
})
export class ChatGateway {
  constructor(private authService: AuthService) {}

  async handleConnection(client: Socket) {
    const token = client.handshake.headers.authorization;
    if (!token) {
      client.disconnect();
      return;
    }
    
    try {
      const user = await this.authService.verifyToken(token);
      client.data.user = user;
    } catch {
      client.disconnect();
    }
  }
}

注意事项

  1. 生产环境应配置更严格的CORS策略
  2. 考虑添加速率限制防止滥用
  3. 可能需要使用Redis适配器进行水平扩展

这样你就完成了一个基本的NestJS实时通信功能。根据需要可以进一步扩展功能。

回到顶部