You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket.io客户端无法连接Next.js自定义服务器问题求助

Socket.io客户端无法连接Next.js自定义服务器排查

问题背景

首次接触WebSockets,基于Next.js搭建了自定义服务器,预期服务端和客户端控制台会打印连接相关日志,但两边均无输出,浏览器控制台出现如下错误:

WebSocket connection to 'ws://localhost/socket.io/?EIO=4&transport=websocket' failed:

服务端代码

const { Server } = require("socket.io");
const express = require("express");
const { createServer } = require("http");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const PORT = process.env.PORT || 3000;
const { MongoClient, ServerApiVersion } = require("mongodb");
const user = require("./server/api/userAPI");
const game = require("./server/api/gameAPI");

// Vanilla API routes
const app = next({ dev, hostname, PORT });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const expressApp = express();
    const httpServer = createServer(expressApp);
    const io = new Server(httpServer);

    expressApp.use(express.json());
    expressApp.use("/user", user);
    expressApp.use("/game", game);

    expressApp.get("*", (req, res) => {
      return handle(req, res);
    });

    io.on("connection", (socket) => {
      console.log("socket connected");
      const count = io.engine.clientsCount;
      console.log(count);
    });

    expressApp.listen(3000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });

  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

客户端代码(app.js)

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

function MyApp({ Component, pageProps }: AppProps) {

  const socket = io();

  socket.on("connect", () => {
    console.log(socket.id); // x8WIv7-mJelg7on_ALbx
  });

  return (
    <WagmiConfig client={wagmiClient}>
        <ChakraProvider theme={theme}>
          <Page>
            <Component {...pageProps} />
          </Page>
        </ChakraProvider>
    </WagmiConfig>
  );
}

export default MyApp;

排查原因及修复方案

1. 核心问题:启动了错误的服务器实例

服务端代码中,你创建了绑定Socket.io的httpServer,但最后调用expressApp.listen(3000)启动的是Express单独的服务器,而非挂载了Socket.io的httpServer。这导致Socket.io并没有运行在正在监听的端口上,客户端无法建立连接。

修复:将expressApp.listen(...)替换为httpServer.listen(...):

httpServer.listen(PORT, (err) => {
  if (err) throw err;
  console.log(`> Ready on http://${hostname}:${PORT}`);
});

2. 客户端连接地址未指定端口

客户端调用io()时,默认会尝试连接当前页面的域名,但错误日志显示连接的是ws://localhost(缺少3000端口),可能是客户端环境中默认地址解析异常。显式指定完整连接地址可以避免这个问题。

修复:修改客户端连接代码:

const socket = io("http://localhost:3000");

3. 版本兼容性问题

确保服务端的socket.io包与客户端的socket.io-client包版本完全一致。版本不匹配会导致握手协议不兼容,引发连接失败。

检查方式:查看package.json中两个包的版本号,确保相同。如果不一致,重新安装对应版本:

# 示例:安装4.7.2版本
npm install socket.io@4.7.2 socket.io-client@4.7.2

内容的提问来源于stack exchange,提问作者kalculated

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:33:21