Dar*_*und 3 websocket socket.io next.js vercel
我正在尝试创建一个下一个应用程序,它也可以通过套接字与其后端实时通信,并且我正在使用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);
});
});
Run Code Online (Sandbox Code Playgroud)
然后在前端:
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);
});
}, []);
Run Code Online (Sandbox Code Playgroud)
这段代码在本地运行得很好,没有任何问题,无论是在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,并且自定义服务器现在正在运行。
归档时间: |
|
查看次数: |
11473 次 |
最近记录: |