将 Nextjs 部署到 Vercel 的 SocketIO,套接字未连接

SocketIO with Nextjs deployed to Vercel, socket is not connecting

我正在尝试创建下一个应用程序,该应用程序还通过套接字与其后端进行实时通信,为此我正在使用 socket.io。它在本地工作得很好(即使在构建时),但是当部署到 vercel 时,我得到 WebSocket connection to '<URL>' failed: WebSocket is closed before the connection is established.

类型的错误

首先我创建了一个自定义 Nextjs 服务器:

import { createServer } from "http";
import { parse } from "url";
import { Server as SocketIOServer, Socket } from "socket.io";
import next from "next";

const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

console.log("hello");

app.prepare().then(() => {
  const server = createServer((req, res) => {
    const parsedUrl = parse(req.url!, true);
    handle(req, res, parsedUrl);
  }).listen(port);

  // tslint:disable-next-line:no-console
  console.log(
    `> Server listening at http://localhost:${port} as ${
      dev ? "development" : process.env.NODE_ENV
    }`
  );

  const socketIO = new SocketIOServer(server, { transports: ["websocket"] });

  socketIO.on("connection", (socket: Socket) => {
    console.log("connected", socket.id);
  });
});

然后在前端:

import { io } from "socket.io-client";

useEffect(() => {
  const socket = io(window?.location?.hostname || "http://localhost:3000", {
    reconnectionDelay: 1000,
    reconnection: true,
    reconnectionAttempts: 10,
    transports: ["websocket"],
    agent: false,
    upgrade: false,
    rejectUnauthorized: false
  });

  socket.on("connect", () => {
    console.log("someone connected: ", socket?.id);
  });
}, []);

此代码在本地运行良好,完全没有问题,在 dev 模式和 build && start 模式下都运行良好。

一旦部署到 vercel,问题就开始了。

如果我不将 ":3000" 添加到 window.location.hostname,我会收到错误消息:

WebSocket connection to 'wss://xxxxxx.vercel.app/socket.io/?EIO=4&transport=websocket' failed: doOpen

如果我加上它,那么它就变成了:

WebSocket connection to 'wss://xxxxxx.vercel.app:3000/socket.io/?EIO=4&transport=websocket' failed: WebSocket is closed before the connection is established.

答案是:

这是不可能的。 Vercel 不支持 Nextjs 具有的自定义服务器功能。耻辱。

问题不在套接字本身,问题在 Vercel 并且由于上述原因它不起作用。

谁遇到了类似的问题,我发现最简单的解决方法就是简单地转移到 Heroku,它们很容易设置(我正前往 DO、GCP、AWS 等,但它们都需要更多时间对于不是 DevOps 人员的人来说,设置起来很费力而且更复杂)。所以我起床 运行 几分钟后使用 Heroku,自定义服务器现在可以正常工作了。