Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io client connection cannot be made on the 2nd time

Currently, I am implementing an API using nodejs express, then it needs to connect to socket.io and send event.

The API is located in socket.io-client (client), and it connects to socket.io (server)

1st API call: success

The connection is made for the 1st call of the API, message is sent and socket can be disconnected, with the 'disconnect' callback is invoked both on client and server side.

2nd API call: failure

When the API is invoked the 2nd time, the connection to server cannot be made, 'client' callback on client side is not called.

3rd API call: success

Then I tried to restart the client side, keeping other things unchanged. The API is called again, and the connection to socket.io is made successfully and everything is fine.

Can anyone explain the logistics behind this?

Updated

client.js

   App.getByUserId(message.to_id, function(error, app) {
  var  socket = io.connect('http://127.0.0.1:9002');
  socket.on('connect', function(){
  console.log("client connect socket id:" + socket.id);
    console.log("appkey:" + app.private_token);
    socket.emit('appkey.check',{appkey: app.private_token, uuid: message.to_id.uuid},    function(data){
        socket.emit("forceDisconnect");
        socket = null;

    });
});
like image 421
Sanvi Lu Avatar asked Sep 21 '13 13:09

Sanvi Lu


People also ask

How many messages per second can Socket.IO handle?

Both server and client node processes use 95-100% of a CPU core each. So pure throughput looks ok. I can emit 100 messages per second to 100 local clients at 55% CPU usage on the server process.

How many concurrent connections can Socket.IO handle?

Once you reboot your machine, you will now be able to happily go to 55k concurrent connections (per incoming IP).

Does Socket.IO have a timeout?

So, you can configure both the server and client side timeout settings by setting the following timeout properties on the engine.io component inside of socket.io.


1 Answers

You just hit one of Socket.IO's many "features" or "bugs" depending how you see this. Socket.IO tries to be smart and re-use connections (which causes a lot of connection issues actually) The way around this is use the force new connection option in your io.connect:

io.connect('http://127.0.0.1:9002', { 'force new connection': true });

What you could also do is use https://github.com/primus/primus which wraps Socket.IO if you use the socket.io transformer. Internally, it completely removes the use of the io.connect and uses the much more lower level io.Socket constructor to create more stable connections that you would get with a stock socket.io.

like image 65
3rdEden Avatar answered Oct 13 '22 19:10

3rdEden