Socket.io Client: Always invalid namespace message
Asked Answered
F

1

8

Server code:

import http from 'http';
import Koa from 'koa';
import { Server } from 'socket.io';


(async () => {
  const app = new Koa();
  var server = http.createServer(app.callback());
  var io = new Server(server, {
    path: '/seacher',
    transports: ['websocket'],
  });

  io.on('connection', (socket) => {
    setTimeout(() => socket.emit('message', { say: 'hello' }), 1000);

    socket.on('message', (msg) => {
      console.log('[msg]', msg);
    });
  });

  server.listen(3000)
})();

Client code:

var socket = io('http://localhost:3000/seacher', {
  path: '/seacher',
  autoConnect: false,
  transports: ['websocket'],
});
socket.on('error', (err) => console.log('error', err));
socket.on('connect', () => console.log('connect'));
socket.connect();

No any messages in browser / nodejs console.

In the Network tab in browser a lot of connections with messages like

enter image description here

Flossie answered 3/12, 2020 at 20:51 Comment(0)
H
25

Change the client code to this:

const socket = io('http://localhost:3000', {     // note changed URL here
  path: '/seacher',
  autoConnect: false,
  transports: ['websocket'],
});

The path option specifies what URL socket.io is going to use internally. You put that in the path option as you have already done in both client and server.

If you put something in the URL you specify like you had 'http://localhost:3000/seacher', then that is the namespace /seacher that you are trying to connect, but your server does not support that namespace.

This is a confusing part of socket.io's design, but path and namespace are not the same thing in socket.io. Do not confuse or mix them.


FYI, there is rarely a reason to customize the path option the way you have done unless you are trying to run more than one socket.io server shared on the same http server (something it does not appear you are doing). By default, the path is /socket.io which makes a lot of sense in logs and debuggers and when accessing the client-side library. I would suggest you remove the path option from both client and server and let it default to /socket.io. And, don't use a path in your connection URL either as that specifies a namespace, not a path.

Hooten answered 3/12, 2020 at 23:59 Comment(4)
@Flossie - Please ask a new question that explains your proxy situation and shows all relevant code.Hooten
Where is that io is being import from ?Southeastwards
@Southeastwards - It's explained in the socket.io doc. You can import it from /socket.io/socket.io.js and it will automatically be served from your server or you can import it from your favorite CDN.Hooten
thanks. this stopped my 3hrs of headacheWilley

© 2022 - 2024 — McMap. All rights reserved.