我已经按照文档创建了一个通过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...