客户端的socket访问失败
使用next + socket.io做一个双人版的wordle小游戏(两人轮流猜词共同完成同一个wordle挑战),在本地执行是没有问题的,但是部署到vercel或者阿里云ECS上的时候,本地的socket连接失败这是什么原因?
我使用端口号来标识每个游戏房间,每个端口号对应着一个服务端的socket和若干个客户端的socket。
服务端
// src/socket/ServerManager.js
import { Server } from "socket.io";
import { log, generateNewState } from "@/utils";
class ServerManager {
constructor(gameStateManager) {
this.io = new Server({
cors: {
origin: "*",
},
});
...
start(port) {
this.io.listen(port);
}
// src/socket/createServerSocket.js
import { generateUniquePort } from "@/utils";
import GameStateManager from "./GameStateManager";
import ServerManager from "./ServerManager";
function createServerSocket() {
const gameStateManager = new GameStateManager();
const serverManager = new ServerManager(gameStateManager);
const port = generateUniquePort();
serverManager.start(port);
return port;
}
当客户端访问/two-player
,返回端口号作为游戏房间的标识。
// src/app/two-player/route.js
export async function GET() {
const roomId = createServerSocket();
return Response.json({ roomId });
}
客户端
发起建立游戏房间的请求
// src/socket/createPlayRoom
function createPlayRoom() {
return fetch("/two-player").then((res) => res.json());
}
组装进入房间的链接
export function generateConnectUrl(roomId) {
return `${window.location.protocol}//${window.location.hostname}:${roomId}`;
}
创建本地socket与服务端socket通信
import { io } from "socket.io-client";
function createClientSocket(url) {
const socket = io(url);
socket.on("connect", () => {
console.log("connect");
});
return socket;
}
错误信息
附: