Search code examples
node.jscometlong-polling

Long Polling for more than 1 connection in same browser


I'm trying to implement long polling technique using NodeJS.

I have this basic code deployed on server.

http = require('http');

function onRequest(request, response) {
    console.log('onRequest reached');
}

http.createServer(onRequest).listen(8080);
console.log('Server has started.');

When requesting localhost:8080, onRequest is fired. When this connection is alive, I request the same page in second tab, but onRequest is not fired. However, requesting same page from another browser fires onRequest while first connection is still "long-polled".

Is there any limitation in browsers? How and why this happens? How can avoid this?

btw. I'm trying to implement long polling chat and notifications system. Actually requests should be made by AJAX call.


Solution

  • It might be that the browser is waiting for a response. Try sending just the headers, immediately:

    function onRequest(request, response) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        console.log('onRequest reached');
    }
    

    Another tip: If you're going to use long polling, I suggest you look into Server-Sent Events. There is pretty wide browser support for this, and there is also a polyfill for older browsers. Here is an example in CoffeeScript showing how you can send events from a node.js server.