Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io Client: Always invalid namespace message

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

like image 581
user1356144 Avatar asked Dec 13 '22 07:12

user1356144


1 Answers

Change the client code to this:

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

like image 110
jfriend00 Avatar answered Dec 28 '22 23:12

jfriend00