【问题标题】:Socket.IO NestJS can't connect : keeps disconnecting / reconnetingSocket.IO NestJS 无法连接:不断断开/重新连接
【发布时间】:2021-04-12 02:37:02
【问题描述】:

我正在尝试将 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的帮助。

【问题讨论】:

    标签: typescript sockets websocket socket.io nestjs


    【解决方案1】:

    看起来您使用的是Socket.IO 版本3,即is not yet supported by Nest。降级到版本 2。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2013-11-21
      • 2012-05-28
      • 2014-04-30
      • 2018-05-31
      相关资源
      最近更新 更多