browser instant updates with ajax/jquery

我的未来我决定 提交于 2020-01-12 10:33:41

问题


I'm trying to reverse engineer how facebook handles their notifications, where when you get a message you get instantly notified via the browser.

I've fiddled with it for a little bit and realized that there is always a pending GET request "listening" if you will to some sort of update from the server. This appears to be some sort of observer pattern. I was just wondering if this pattern was documented somewhere.


回答1:


The technique is actually called Long Polling. This is one of the popular Comet techniques to get around the limitations of traditional polling.

You may want to check out the following Stack Overflow post for a very simple example:

  • Simple “Long Polling” example code?

UPDATE:

In addition to the above, I suggest that you check out the accepted answer to the following Stack Overflow post for a detailed description of the technique:

  • How does facebook, gmail send the real time notification?



回答2:


The technique is called Comet, aka 'server push'

There are currently 2 main ways of implementing comet.

1) As Daniel mentioned, long-polling, where you can use ajax to leave a hanging request to the browser that doesn't send the response back until the server decides to (whether it be based on someone else's actions or another server event).

2) The second approach, used by Google, is streaming. This involvs using ajax to leave a hanging request, but the response is never sent back to you, ever. Instead, the server updates bits of data and you use javascript to monitor changes, and fire events based on new data being pushed in. What happens is you get one very long continuous stream of data flowing in on a document that never closes, taking new data as it comes in.

HTML5 has a specification for a simpler way to do this with Web-Sockets. In the future, this type of live web-app will become commonplace as Web-Sockets are easy to use, but it is not supported on all browsers yet.

If you want to build a Comet site for production, you'll need to use a non-blocking I/O async server like one of the following.

http://www.tornadoweb.org/ - python

http://nodejs.org/ - server side javascript

-- or google for comet servers.

You'll need to know how to program for comet type apps on the server-side, as the javascript for Comet is pretty trivial, just your normal ajax calls with a couple event handlers.



来源:https://stackoverflow.com/questions/2680387/browser-instant-updates-with-ajax-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!