普通的HTTP请求

  1. 客户端向服务器端发送一个页面请求
  2. 服务器端计算该请求的响应
  3. 服务器端将应用发送到客户端

AJAX轮询

  1. A client requests a webpage from a server using regular http (see http above).
  2. The requested webpage executes javascript which requests a file from the server at regular intervals (e.g. 0.5 seconds).
  3. The server calculates each response and sends it back, just like normal http traffic.

AJAX长轮询

  1. A client requests a webpage from a server using regular http (see http above).
  2. The requested webpage executes javascript which requests a file from the server.
  3. The server does not immediately respond with the requested information but waits until there's new information available.
  4. When there's new information available, the server responds with the new information.
  5. The client receives the new information and immediately sends another request to the server, re-starting the process.

HTML5服务端事件

  1. A client requests a webpage from a server using regular http (see http above).
  2. The requested webpage executes javascript which opens a connection to the server.
  3. The server sends an event to the client when there's new information available.
    • real-time traffic from server to client, mostly that's what you'll need
    • you'll want to use a server that has an event loop
    • not possible to connect with a server from another domain

If you want to read more, I found thse (article), (article), (article), (tutorial) very useful.

HTML5 WebSocket

  1. A client requests a webpage from a server using regular http (see http above).
  2. The requested webpage executes javascript which opens a connection with the server.
  3. The server and the client can now send each other messages when new data (on either side) is available.
    • real-time traffic from the server to the client and from the client to the server
    • you'll want to use a server that has an event loop
    • with WebSockets it is possible to connect with a server from another domain.

It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!

If you want to read more, I found thse (article), (article) (tutorial) very useful.

Comet是一种用于web的推送技术,能使服务器实时地将更新的信息传送到客户端,而无须客户端发出请求,目前有两种实现方式,长轮询和iframe流。参照文章:Coment [en]Coment [zh_CN]Reverse Ajax, Part 1: Introduction to Comet

通讯方式 浏览器支持 实时性 应用复杂度 说明
普通的HTTP请求 非常好 静态 简单 -
AJAX轮询 一般 简单 很难选择轮询的时间间隔,可能会对服务器造成比较大的性能压力
AJAX长轮询 实时 复杂 服务器端需要使用异步IO模型
HTML5服务器端事件 实时 一般 浏览器支持相对较差,服务器端到客户端单向传输数据
HTML5WebSocket 一般 实时 一般 新型浏览支持比较好,服务器端标准相对比较成熟
Socket.io 非常好 实时 简单 通过自动降级实现,服务器端和客户端支持都比较完善

判断浏览器支持情况:

  1. HTML5test
  2. Can I use…

  1. Socket.io - http://socket.io/