我正在努力了解Facebook的聊天功能如何接收消息,而不用连续地分配服务器。
Firebug向我展示了一个持续坐在那里的GET XmlHttpRequest,等待服务器的响应。 5分钟后,这个从来没有超时。
他们如何防止超时?
AJAX请求可以无限期地坐在那里,等待响应?
我可以用JSONRequest来做到吗?我在json.org看到这个:
JSONRequest is designed to support
duplex connections. This permits
applications in which the server can
asynchronously initiate transmissions.
This is done by using two simultaneous
requests: one to send and the other to
receive. By using the timeout
parameter,a POST request can be left
pending until the server determines
that it has timely data to send.
Facebook使用现在称为
Comet的技术将消息从服务器推送到客户端,而不是让客户端轮询服务器。
有很多方法可以实现,XMLHttpRequest long polling只是一个选择。这种方法的原理是,客户端发送一个普通的XMLHttpRequest,但服务器在发生某些事件(例如另一个用户发送消息)之前不会响应,所以客户端被迫等待。当客户端收到响应(或者请求超时)时,客户端只需创建一个新请求,使其始终有一个打开的请求到服务器。