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?
The principle is rather simple:
- clients sends a request to server and keeps connections alive;
- server keeps a handle on the connection and waits;
- when updates are available, server sends back data to client;
- (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.
With most programming languages aimed at developing desktop solutions (or "heavy" clients), you'd usually resort to your usual network tools: sockets.
If we're talking about a rich web-client to build in a browser-based solution, you have the option to:
- use your usual
XMLHttpRequestobject (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
WebSocketAPI 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...