skip to Main Content

I have created a demo project to implement websocket via socket.io following the documentation. However, when I try to fetch all open sockets from the server using fetchSockets() function mentioned in the docs https://socket.io/docs/v4/server-api/#serverfetchsockets, the webserver crashes and I recieve error message 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...

2

Answers


  1. Chosen as BEST ANSWER

    Upgrade socket.io to version 4

    npm un socketio
    npm i socket.io
    

  2. As I said in my comment io.fetchSockets() was introduced in socket.io version 4 so you need to upgrade both client and server to v4.

    The only other way you could get that error (even when running socket.io v4) is if io isn’t what you actually think it is. But, the code as you show in your question it has a proper value for io and it’s declared const so it isn’t likely that issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search