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

调用Socket.IO的fetchSockets()时报错TypeError的技术求助

问题:调用Socket.IO的fetchSockets()函数报错TypeError: io.fetchSockets is not a function

我按照官方文档创建了一个通过Socket.IO实现WebSocket的演示项目,但当尝试使用fetchSockets()函数从服务器获取所有开放套接字时,Web服务器崩溃,收到错误信息:TypeError: io.fetchSockets is not a function。

服务端代码

const express = require("express");
const Server = require("socket.io");

const app = express();

app.use(express.static(__dirname + "/public"));

const webserver = app.listen(9001, () => {
  console.log("Running on port 9001");
});

const io = new Server(webserver);

io.on("connect", async (socket) => {
  console.log(socket.id + "client connected!");
  
  // Fetch open sockets and log them
  const sockets = await io.fetchSockets();
  console.log(sockets);
});

客户端HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io("http://localhost:9001");

    socket.on("connect", () => {
      console.log("connected!");
    });
  </script>
</body>
</html>

返回的错误信息

[nodemon] starting `node index.js`
Running on port 9001
GkBIw5SD_7qGcDxJAAAAclient connected!
/home/euna/sandbox/testsockets/index.js:18
  const sockets = await io.fetchSockets();
                           ^
TypeError: io.fetchSockets is not a function
    at Namespace.<anonymous> (/home/euna/sandbox/testsockets/index.js:18:28)
    at Namespace.emit (node:events:514:28)
    at Namespace.emit (/home/euna/sandbox/testsockets/node_modules/socket.io/lib/namespace.js:209:10)
    at /home/euna/sandbox/testsockets/node_modules/socket.io/lib/namespace.js:176:14
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11)

Node.js v18.17.0
[nodemon] app crashed - waiting for file changes before starting...

解决方案

  • 检查并升级Socket.IO版本:fetchSockets()是Socket.IO v4.x版本新增的API,v3.x及以下版本没有这个方法。执行以下命令查看当前版本:

    npm list socket.io
    

    如果版本低于v4,执行升级命令:

    npm install socket.io@latest
    
  • 确认调用对象正确性:确保io是Socket.IO的Server实例(你的代码里已经正确创建了Server实例,这一步主要排查其他可能的误用场景)。fetchSockets()是Server实例的方法,不能在Namespace对象上调用。

  • 验证修复效果:升级完成后重启服务器,重新连接客户端,此时io.fetchSockets()应该能正常返回当前所有连接的Socket实例数组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:05:19