Sachin
Sachin

Reputation: 2775

How client gets updates from server without frequent ajax request?

In my project, there are features like private chat and message notification. Message notification let as know if there are any new unread messages.


For achieving that , the idea that came into my mind is

Like in a client - server model , the server should listen for the new requests. Like that , I thought there should be some mechanism to listen to the server for getting information about new messages . Since I know ajax , I used ajax request with an interval of 2seconds.

The ajax requests while checking it in chrome will be something like below . Ajax requests under network section in chrome

But I thought afterward that, StackOverflow should use the same trick if it was the only idea to do so since they update notifications / vote information asynchronously .

Checking their ajax requests in chrome, it was completely blank.

I need to know how it can be achieved without using frequent ajax requests (which will increase the load on the server).
A simple example with the most efficient technique would be very useful for learning.

Upvotes: 11

Views: 2681

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

What @Amadan mentioned is perfectly fine but StackOverflow and other StackExchange website mainly use WebSocket for modern browsers (which supports HTML5 and WebSocket).

Open Developers Console in Chrome. Go to Network Tab, and apply WS or WebSocket filter and refresh the page. You will see something like below:

enter image description here

Upvotes: 5

Amadan
Amadan

Reputation: 198476

This is known as Comet, and there are several ways to achieve it:

  • Polling (what you are doing - check in regular intervals if there is a message)
  • Long-polling (making a request that doesn't get a response until there is a message)
  • Streaming (opening a script connection that sends executable JavaScript updates incrementally)
  • Websockets (the best option, if supported - all the rest were hacks for what Websockets were finally made to address)

Implementing them is tricky and here are many libraries to choose from that implement them correctly for you (e.g. Socket.IO).

EDIT:

A simple example with the most efficient technique would be very useful for learning.

As I said, you don't want to be implementing those yourself, as they're tricky and full of peril; most good Comet libraries take into account browser's features and choose the best protocol, so that it is transparent for the programmer, making it very easy to develop with this model. For example, check out Socket.IO tutorials.

Also note that you need a server that is equipped to deal with Comet: e.g. Socket.IO works with Node.JS. They will not work with default Apache, for instance.

Upvotes: 12

Related Questions