17

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?

Amar
  • 11,930
  • 5
  • 50
  • 73
  • here is the question I asked a while ago http://stackoverflow.com/questions/13666872/php-chat-application-questions – BLOB Dec 27 '12 at 08:48
  • 2
    This might be a good start : http://www.google.com/search?q=google+comet+programming – Pranav 웃 Dec 27 '12 at 08:48
  • Thanks Pranav, I knew it too :) So does skype,gtalk etc all use this technique itself or are there any other ways? – Amar Dec 27 '12 at 08:51
  • 2
    WebSocket is a very good solution if your browsers support the functionality (from IE10 only) : http://code.google.com/p/phpwebsocket/ – sdespont Dec 27 '12 at 08:55

1 Answers1

25

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

Maurice
  • 1,223
  • 14
  • 21