How does facebook take care of their “real-time” data? if you’re viewing your activity feed and a user likes something, you can instantly see a change of text saying that that user liked it, or when you’re notified, you’ll see a red notification sign while on the page without refreshing.
I know that this code can push data without refreshing:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
But can someone explain how to push real-time data so other users will be able to see updates while on their page without refreshing.
Thanks
This can be implemented using various techniques, which have many names: Long-polling, Server Sent Events, Comet, WebSockets, and others.
Basic idea is this:
Alice opens facebook. Her browser makes a request for updates (
$.get, for example), but the server does not respond if there are no new updates and the request remains in ‘waiting’ state.Bob opens facebook. He decides to comment on Alice’s wall. His browser posts his comment to the server (
$.post).Alice’s browser finally gets a response to this long hanging request and happily draws a red “1” in the notification area. It also immediately opens another update request (to not miss any).
Alice sees comment from Bob, which was delivered instantly.
The technique described is called “long polling” and it was first introduced by Google in Gmail.