1

I'm implementing a very basic long-polling scenario in my web-app to get server notifications. That's my client-side code

(function poll()
{
    $.ajax({ url: "server.php", success: function( data )
    {
        // data management

    }, dataType: "json", complete: poll, timeout: 15000 });    
})();

On the server side there is a simple while(true) loop that waits for a new message and then prints out the result. It works; it's, however, not working as it should: the message sent from the server is received by the client whenever the timeout expires and the function poll is called again and not whenever the server fires up the notification (as it is supposed to be).

Any ideas why it's working as a "setInterval" and not as it should? Thanks

Socket2104
  • 122
  • 2
  • 9
  • 1
    *"the message sent from the server is received by the client whenever the timeout expires and the function poll is called again"* that's exactly how it's supposed to work. That's why long polling is inefficient compared to websockets. Long-polling requires sending a request to the server with a timeout. If no response happens within the timeout, the request ends and a new one is sent. you should limit your php to a similar timeout. – Kevin B Nov 18 '13 at 20:22
  • In that case what's the difference between this technique and a "normal" polling method? Something misleaded me, I thought it could work as a "socket recv()" or so – Socket2104 Nov 18 '13 at 20:26
  • The difference is you're only sending a request every 15 seconds rather than every second, while still receiving notification of changes/new information near-instantly. – Kevin B Nov 18 '13 at 20:27
  • Let's say a 15 seconds timeout, if the server fires up a notification on the "first second" I have to wait 14 seconds again to get the message on the client-side and that's basically the same as firing up a 15 secs setInterval. Am I wrong? – Socket2104 Nov 18 '13 at 20:32
  • 1
    No, in that case the complete callback would happen in that first second, thus causing the poll to start immediately. – Kevin B Nov 18 '13 at 20:32
  • Got it, thank you. The only alternative would be using websockets? – Socket2104 Nov 18 '13 at 20:33
  • possible duplicate of [Why setting a client-side timeout when using long polling?](http://stackoverflow.com/questions/14903223/why-setting-a-client-side-timeout-when-using-long-polling) – Paul Sweatte Oct 22 '14 at 19:56

0 Answers0