本文介绍了Socket.IO NestJS 无法连接:不断断开/重新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm trying to use Socket.IO with NestJS.When i load the front, i get a lot of connections and disconnections to the nestjs gateway.

看到这个:

[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 永远不会发生.

The "Connected" console.log never happens.

这里是我的客户端简单代码:

Here my client simple code :

<!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 网关:

And here my nestJS gateway :

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 请求选项卡的屏幕截图:

Here a screenshot of my chrome requests tab :

Chrome 上的 WebSocket 选项卡是空的.

The WebSocket tab on chrome is empty.

我一步一步地跟着几个教程,我找不到问题.

I followed several tutorials steps by steps, and i cant find the issue.

非常感谢 oyu 的帮助.

Thank oyu very much for your help.

推荐答案

看起来您正在使用 Socket.IO 版本 3, Nest 尚不支持.降级到版本 2.

Looks like you're using Socket.IO version 3, which is not yet supported by Nest. Downgrade to version 2.

这篇关于Socket.IO NestJS 无法连接:不断断开/重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 12:55