Socket.io connection to server doesn't work sometimes

Problem

I have setup a Node.JS server with socket.io on a VPS and I broadcast every 10 seconds the number of connected clients to all. This usually works fine, though often times, the connection can't be established and I get this error (I changed the IP a bit):

GET http://166.0.0.55:8177/socket.io/1/?t=1385120872574

After reloading the site, usually the connection can be established, though I have no idea why the failed connection happens in the first place, also I don't know how to debug the socket.io code. Sometimes I can't connect to the server anymore and I have to restart the server.

Additional information:

  • My main site runs on a different server (using a LAMP environment with CakePHP) than the Node.js server.
  • I use forever to run the server
  • I have a lot of connected clients (around 1000)
  • My VPS has 512 MB Ram and the CPU is never higher than 25%
Problem courtesy of: Christian Strang

Solution

After top command, try:

socket.on('error', function (err) { 
   console.log("Socket.IO Error"); 
   console.log(err.stack); // this is changed from your code in last comment
});

Also, you could try a the slower transport. Socket.io use Websocket by default but if your server cannot allocate enough resource, you can try another transport which is slower but use less resources

io = socketIo.listen(80);
io.set('transports', ['xhr-polling']);
Solution courtesy of: Paiboon Panusbordee

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.