HTTP Client-Server – Better Server to Client Communication Mechanism

client-serverhttpinternet

I have a single server with several clients. I want to push messages to a particular client at a given time. Clients should not polling to the server. what are good patterns and practices to solve this problem?

Best Answer

You can use a technique often referred to long-polling or comet, which allows to implement a "push"-based event/update system.

Principle

The principle is rather simple:

  1. client sends a request to server and keeps connections alive;
  2. server keeps a handle on the connection and waits;
  3. when updates are available, server sends back data to client;
  4. (depending on client-side tech) client may need to send a new request.

This way the clients don't poll regularly. However, that implies that a significant number of connections might be kept alive at any single given time, so make sure you understand the implications of this approach for your server.

How to Implement It?

So, the underlying principle remains the same no matter what your platform is: as long as you can send an HTTP request and wait for the response synchronously or asynchronously, you have a way to implement long-polling.

Heavy Clients

With most programming languages aimed at developing desktop solutions (or "heavy" clients), you'd usually resort to your usual network tools: sockets.

Lightweight/Rich Clients

If we're talking about a rich web-client to build in a browser-based solution, you have the option to:

  • use your usual XMLHttpRequest object (the server will only reply once it's got something to send back, at which point the client will either re-initiate another connection or use a spare one if it opened multiple ones to ensure there's always multiple channels opened at hand),
  • or to use <script> tags that query a URL sending back a payload wrapped in a call to function defined in the client's context (see JSONP),
  • or to use WebSocket API introduced with HTML5,
  • or a variation of the above or using an external tool (Java Applet, Flash, etc...) to achieve the same effect.

Beware that, as is often the case with web techs, cross-browser support is going to require extensive testing, and you may be forced to use a combination of the above techniques if you target hostile browser market shares...

Related Topic