我已经按照文档创建了一个通过Socket.IO实现WebSocket的演示项目.然而,当我try 使用文档https://socket.io/docs/v4/server-api/#serverfetchsockets中提到的fetchSockets()函数从服务器获取所有打开的套接字时,Web服务器崩溃,并收到错误消息TypeError: io.fetchSockets is not a function.

Server side code

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);
});

My client side code in html page

<!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>

The Error message returned

[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...

推荐答案

正如我在 comments 中所说,io.fetchSockets()是在Socket.IO版本4中引入的,因此您需要将客户端和服务器都升级到v4.

如果io不是您实际认为的那样,您可能得到该错误的唯一其他方式(即使在运行Socket.IO v4时).但是,正如您在问题中显示的代码,它有一个正确的值为io,它被声明为const,所以这个问题不太可能出现.

Javascript相关问答推荐

在JavaScript中,如何将请求的回调函数的结果合并到运行的代码中?

创建1:1比例元素,以另一个元素为中心

如何提取Cypress中文本

在JavaScript中对大型级联数组进行切片的最有效方法?

如何在表格上拥有水平滚动条,在正文页面上拥有垂直滚动条,同时还对html表格的标题使用位置粘性?

将状态向下传递给映射的子元素

在观察框架中搜索CSV数据

成功完成Reducers后不更新状态

用JavaScript复制C#CRC 32生成器

在Three JS中看不到补间不透明度更改效果

如何在JavaScript文件中使用Json文件

JS—删除对象数组中对象的子对象

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

OpenAI转录API错误请求

为什么在函数中添加粒子的速率大于删除粒子的速率?

无法设置RazorPay订阅API项目价格

如何使用Reaction路由导航测试挂钩?

使用静态函数保存 node 前的钩子

在对象的嵌套数组中添加两个属性

如何在函数组件中保留对计时器的引用