Reputation: 8597
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
Upvotes: 2
Views: 931
Reputation: 230521
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.
Upvotes: 6
Reputation: 621
There are several solutions to this problem and you will have to do some research to decide which you want to implement. Some of these solutions are collectively reffered to as Comet (http://en.wikipedia.org/wiki/Comet_%28programming%29)
The method used by Facebook is Ajax Long Polling. In this method an ajax call is made to to the server and the server waits to respond, leaving the connection hanging, until it has an update or a maximum amount of time is reached. If new data is received during that interval, say a chat message, it responds immediately with the data. At the end of each call the client then starts a new ajax call and waits. If you watch your browser console on Facebook you can see these calls.
The next method is called a forever frame, where a hidden iFrame is used and sent chunked date continuously and never finishes loading. This data is read by the main frame as it is recieved.
Another solution which is just becoming available is WebSockets. WebSockets is a truly bidirection persistent connection for browsers and is very powerful. It is however in it's early stages and until a recent revision was blocked by some browsers do to security concerns.
Upvotes: 2
Reputation: 679
Upvotes: 0