Search code examples
phpjavascriptapacheapilong-polling

Apache, javascript and PhoneGap : What's the best way to listen to some random event ? Interval or long polling?


I'm building an app in which the client (PhoneGap) is waiting for some event to be triggered from another client !

So of course the schema would be: Client1 one send a message (name, message and target(client2)) - Server - Client 2 receive the message (from client1, message, client1.name) this can happen every second or every hour. No rules. It can also happen only once or never ..

I've a lot of examples about long polling like here: How do I implement basic "Long Polling"?

I know it's bad to use it with Apache. So I'm wondering if in this case I should use setInterval instead?

Should I set up an interval to ask the server to check the DB if I previously recorded any message from a client to another one and deliver it ? or is this a bad way to go?

Please advise, thanks :)


Solution

  • This will depends on the frequency in which the messages are being sent and if you require to handle them in real-time basis. If that is the case I would consider implementing HTML 5 Web Sockets.

    Here is a good article that could get you started, if you read it to the end you will see that there is a solution to cross browser issues as well (using socket.io library) that would fallback to long polling and other techniques to achieve what you want.

    If you don't need to handle the messages in real-time and is ok for your application to wait a certain period of time to execute some action based on a message already stored in a repository such as a Database, I would use javascript web workers with a setInterval to call a REST service checking for those messages. Here is a good article related to that.

    The reason to use web workers is that they won't block the UI while checking for new messages, so the usability will be better.

    Here is a small example of a web worker:

    Using the webworker

    var worker = new Worker("http://mydomain.com/worker.js");
    
    worker.onmessage = function(event) {
       //new message received, do something in the UI
    }
    
    worker.postMessage("start");
    

    Web Worker (worker.js)

    this.onmessage = function(event) {
       postMessage("worker started");
    }
    
    //Period of time to check for the messages
    setInterval(function() { getNewMessage() }, 5000);
    
    function getNewMessage() {
       //Call your REST service here and respond back to the main js thread if a new
       //message is received
       postMessage("New message received!");
    }
    

    Hope this helps