Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io client can not connect to localhost while it can connect to 127.0.0.1

I have a server set up using node.js and I'm trying to connect to the server with socket.io. The server used to work perfectly 2 months ago but for some reason it does not work anymore. The server code looks like the following:

var http = require('http');
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

var io = require('socket.io')(server);    

io.sockets.on('connection', function (socket) {
 console.log ('Client connected.'); });

console.log ('Server started.');
server.listen(3000, '0.0.0.0');

On my client side, I'm using the line

socket = io.connect("http://localhost:3000");

to try to connect to my server, but it doesn't work. The connection works perfectly if I use the line

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

If I type localhost:3000 on the browser, it sends me to the page saying Hello World as intended, same as 127.0.0.1, so it is not working only when I'm using io.connect.

Things that I have tried are:

  • changing the host file (adding the line 127.0.0.1 localhost, removing the line including ::1, making a new host file and overwriting it)
  • trying it on a different machine, still the same problem
  • resetting the router settings.
  • pinging localhost on a cmd prompt, it says reply from ::1: time<1ms
  • installing different version of socket.io and node.js (both the most recent ones and versions 2 months ago)

Considering what happens from web browser, localhost seems to work but it only does not work when I use socket.io with it. I have been unable to solve this problem that suddenly appeared, so I would appreciate it a lot if someone can give me some insights on what can be causing this.

like image 962
Kyangi Avatar asked Oct 29 '22 12:10

Kyangi


1 Answers

It seems like an IPv4/IPv6 issue. You may try changing this:

server.listen(3000, '0.0.0.0');

to this:

server.listen(3000, '::1');

or this:

server.listen(3000);
like image 121
rsp Avatar answered Nov 15 '22 06:11

rsp