What does "xhr-polling" config do in socket.io?

Michael Eilers Smith picture Michael Eilers Smith · Feb 11, 2012 · Viewed 12.2k times · Source

I have a node.js server with socket.io:

var io = require('socket.io').listen(app);

// assuming io is the Socket.IO server object
io.configure(function () { 
      io.set("transports", ["xhr-polling"]); 
      io.set("polling duration", 10); 
    });

io.sockets.on('connection', function(socket){
  console.log('connected: %s', socket.id);
  ...
}

With xhr-polling and a polling duration of 10 seconds, does this mean that a new connection will be invoked every 10 seconds? If so, how can I keep track of users if they keep disconnecting? I'm running node.js on heroku.

Answer

Bruno Gagnon-Adam picture Bruno Gagnon-Adam · Aug 8, 2012

xhr-polling means that your server will be waiting for 10 seconds on any GET of POST received that it does not have an answer before answering instead of sending back an empty response. So, if your server has no information to give back after 10 seconds, it will answer back with an empty response. You can read more here : Long polling

I personally use xhr-polling as a fallback option from WebSockets in an application on nodejitsu (another node hosting like Heroku) and it is working fine. The only thing is the "on connection" event that takes about 3-8 seconds instead of being instant as with my WebSocket application.

There is no new connection that is created on every new polling, it is just a way that only one GET or POST is sent to the server every 10 seconds, instead of having to poll the server every .5 seconds to have a "real-time" application. If the server answer in less than 10 seconds, there will be another poll sent to prepare the next answer.

I hope this will help you. Have a good day.