Reputation: 2775
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 usedajax
request with an interval of 2seconds.
The ajax requests while checking it in chrome will be something like below .
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
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:
Upvotes: 5
Reputation: 198476
This is known as Comet, and there are several ways to achieve it:
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