首页 > 解决方案 > WebSocket SocketIO 连接不适用于 Heroku 上的 NestJS 服务器并在 Vercel 上响应客户端

问题描述

我有在 herokou.com 上运行的#NestJS 服务器和在 vercel.com 上运行的 react CRA 应用程序我正在尝试使用 websockets (socket.io) 连接前端和后端但是没有建立连接。在控制台中,网络请求没有显示错误,但 GET 请求对应于 socket.io 超时。没有回应。这就是nestjs网关的编写方式。我可以看到网关的日志正在初始化。但是,即使我尝试打开客户端,也没有连接/断开连接的日志。

@WebSocketGateway()
export class AppGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  users: Record<string, any> = {};
  @WebSocketServer() server;
  afterInit(server: any) {
    this.logger.log('Initialized');
  }
  handleConnection(client: any, ...args: any[]) {
    console.log('connected.');
    if (!this.users[client.id]) {
      this.users[client.id] = client.id;
    }
    client.emit('yourID', client.id);
    this.server.emit('allUsers', this.users);
  }

在客户端我是这样连接的

    socket.current = io.connect(
      "https://server.herokuapp.com:" + props.port
    );

我检查过 props.port 没问题。只是开发者工具窗口的网络请求中的GET请求超时,没有响应。示例: https ://server.herokuapp.com:43030/socket.io/?EIO=3&transport=polling&t=NAq8j0w 此 GET 无响应并超时。

标签: reactjsherokuwebsocketsocket.ionestjs

解决方案


我认为在客户端,初始化 socket.io 的方法是

import io from "socket.io-client";

const socket = io("http://DOMAIN:IP"); // or https

或者如果你想在一个反应​​ Ref 挂钩中使用它:

const socket = useRef();
socket.currect = io("http://DOMAIN:IP");  // or https

或者在一行中我认为:const socket = useRef(io("http://DOMAIN:IP")); // or https


推荐阅读