首页 > 解决方案 > Socket.IO NestJS 无法连接:不断断开/重新连接

问题描述

我正在尝试将 Socket.IO 与 NestJS 一起使用。当我加载前端时,我得到了很多与 nestjs 网关的连接和断开连接。

看到这个:

[Nest] 12232   - 01/06/2021, 11:28:24 AM   [NotificationGateway] Client connected: a2f47PSPB9oUn74AACr
[Nest] 12232   - 01/06/2021, 11:28:30 AM   [NotificationGateway] Client connected: NPBzcFBJLHAkQmcAACs
[Nest] 12232   - 01/06/2021, 11:28:30 AM   [NotificationGateway] Client disconnected: hM8j9f9Fd6zT2HJiAACn
[Nest] 12232   - 01/06/2021, 11:28:36 AM   [NotificationGateway] Client disconnected: kx6x1FMIPqfPNZa9AACo
[Nest] 12232   - 01/06/2021, 11:28:36 AM   [NotificationGateway] Client connected: hHWW5iusE86GaszSAACt
[Nest] 12232   - 01/06/2021, 11:28:42 AM   [NotificationGateway] Client connected: V3ah407F2uCge4GxAACu
[Nest] 12232   - 01/06/2021, 11:28:42 AM   [NotificationGateway] Client disconnected: c-VEB3fnPCWGt8hlAACp
[Nest] 12232   - 01/06/2021, 11:28:48 AM   [NotificationGateway] Client connected: NGuWrdwUQiKigGspAACv

“已连接”的 console.log 永远不会发生。

这是我的客户简单代码:

<!doctype html>
<html>
    <head>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.js'></script>
        <script>
            const socket = io.connect('http://127.0.0.1:3000/');
            socket.on('connected', function() {
                console.log("connected !");
            });
            socket.connect();
        </script>
    </head>
    <body>
    </body>
</html>

这里是我的nestJS网关:

interface SockClient {
  uid: string;
  sock: Socket;
}

// @Injectable()
@WebSocketGateway()
export class NotificationGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  constructor(
    @Inject(forwardRef(() => NotificationService))
    private readonly notificationService: NotificationService,
    @Inject(forwardRef(() => HttpService))
    private readonly httpService: HttpService,
  ) {}

  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('NotificationGateway');

  private clients: SockClient[] = [];

  @SubscribeMessage('authenticate')
  async handleAuth(client: Socket, payload: string): Promise<void> {
    const { uuid, role } = await sendAuthAPICall(this.httpService, payload);
    if (role !== 'pro') {
      this.logger.warn(`Client authentication error ${payload}`);
      client.emit('error', 'authentication error');
      return;
    }
    this.clients.push({ sock: client, uid: uuid });
    this.logger.log(`Client authenticated : ${uuid}`);
  }

  afterInit(server: Server) {
    this.logger.log('Init');
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`);
    this.clients = this.clients.filter((c) => c.sock.id !== client.id);
  }

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`);
  }

  public sendNotification(notif: CreateDto, userId: string) {
    const client = this.clients.find((c) => (c.uid = notif.proId));
    if (!client) return;
    client.sock.emit('notification', notif.title, notif.description, userId);
  }
}

这是我的 chrome 请求选项卡的屏幕截图:

在此处输入图像描述

chrome 上的 WebSocket 选项卡为空。

我一步一步地遵循了几个教程,但我找不到问题。

非常感谢 oyu 的帮助。

标签: typescriptsocketswebsocketsocket.ionestjs

解决方案


看起来您使用的是Socket.IO版本 3,Nest 尚不支持该版本。降级到版本 2。


推荐阅读