I know that we can do this by polling for changes in regular intervals. And this can be achieved by AJAX (for example using jQuery.load()
along with setInterval()
).
But I want to know that are there other methods to do this? Other less costly methods or more efficient methods? What logic an awesome chat client follows? As as soon as you start typing, the other end gets to know that you are typing.
What mechanism do we follow here on stackoverflow to update the upvote count or to show that an edit has been made etc. etc. without the page being refreshed?
AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
When it comes to keeping the client and server in-sync in (near) real-time, there are 3 things that immediately come to mind:
long polling: you already mentioned this one, where you have a timer set on the client which triggers a new AJAX request every 10 seconds or so. This is probably the most "low tech" of the 3 as well as the least efficient; BUT it is also the most compatible (meaning it will work in all browsers, even things like IE6/7)
WebSockets: sdespont already mentioned this one in the comments. While WebSockets a more efficient than long-polling (since it just keeps the two way client-server communication open indefinitely), it can be a very heavy-handed solution if all you're trying to do is get regular updates from the server. All versions from Firefox and Chrome support it, and IE added support in IE10
Server-sent events: this one seems to be less popular (or just not as well known). It allows the server to send changes to the client (as oppose to the client requesting changes from the server, as is the case with long-polling). This is also just a one-way communication (server --> client) and the connection gets closed after the request is complete (as oppose to WebSockets where 2-way communication stays open). Once again, not all browsers support it, and there is no IE support at all
This is also a good article which explains the difference between the more modern ways of client-server communication. And if you want more info about Server-sent events, this is a good write up
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With