Search code examples
socket.iosocket.io-client

socket.io client 's namespace invalid


I am running on the latest version of socket.io, the server code and client code below works well.

// server
const {Server} = require("socket.io"),
  http = require('http');
const httpserver = http.createServer();
io.on("connection", async (socket) => {
  socket.on("error", (err) => {
    console.log(err.message);
  });
  socket.on('disconnect', function () {
    console.log('socket disconnect');
  })
});

const io = new Server(httpserver, {
  cors: {origin: "*", methods: ["GET", "POST"],}
});
httpserver.listen(3001, () => {
  console.log('listening on *:3001');
});

// client
import {io, Socket} from "socket.io-client";

const socket = io('ws://127.0.0.1:3001', {
  transports: ["websocket"]
});

socket.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});

then I tried to work with namespace in socket.io

// server
io.of("device").on("connection", async (socket) => {
  socket.on("error", (err) => {
    console.log(err.message);
  });
  socket.on('disconnect', function () {
    console.log('socket disconnect');
  })
});

// client
const socket = io('ws://127.0.0.1:3001/device', {
  transports: ["websocket"]
});

running the code gives me an error saying 'connect_error due to Invalid namespace''

I can't figure out what goes wrong


Solution

  • Using ws://127.0.0.1:3001/device means you are trying to reach the namespace named '/advice', which does not exist on the server.

    I think you are looking for the path option instead:

    const socket = io("ws://127.0.0.1:3001", {
        path: "/device",
        transports: ["websocket"]
    });
    

    References: