Home > database >  Socket.io client in NodeJS
Socket.io client in NodeJS

Time:01-06

I want to build a microservice infrastructure with nodejs services and a master service, the communication between these services should happen via socket.io, i've setup my socket.io server, but their browser client (socket.io-client) is not working in nodejs (i guess it uses some browser only APIs). Is there a way to create a nodejs socket.io (NOT WEBSOCKETS) client?

EDIT

My client side code:

import { io } from "socket.io-client";
const socket = io("127.0.0.1:3000");

socket.on("connect", () => {
  console.log(socket.id);
});

socket.on("disconnect", () => {
  console.log(socket.id);
});

My server side code:

import { Server } from "socket.io";
const io = new Server();

io.on("connection", (socket) => {
  console.log(socket)
});

io.listen(3000);

Both are written in typescript, the package versions are:

socket.io: ^4.4.0

socket.io-client: ^4.4.0

The Problem is, that i don't get any logs in my console, so i think there is something wrong with client, because socket.io does not mention node in there client side compatiblity graph.

enter image description here

CodePudding user response:

The problem is that you have to pass a valid URL here:

const socket = io("127.0.0.1:3000");

I have no idea why socket.io doesn't give you an error, but if you change that to:

const socket = io("http://127.0.0.1:3000");

Then, it will work.


If you set DEBUG=socket.io-client in your environment, it won't show you an error, but it will show you that it's trying to connect to:

undefined//127.0.0.1:3000

which would give you a clue, I guess.

If you set DEBUG=* in your environment, you will get a lot more debug info (so much that it's a bit hard to sort through).


Set Logging and Debugging Socket.io for more info.

  •  Tags:  
  • Related