WebSocket官方文檔翻譯——About HTML5 WebSockets

About HTML5 WebSockets

The HTML5 WebSockets specification defines an API that enables web pages to use the WebSockets protocol for two-way communication with a remote host. It introduces the WebSocket interface and defines a full-duplex communication channel that operates through a single socket over the Web. HTML5 WebSockets provide an enormous reduction in unnecessary network traffic and latency compared to the unscalable polling and long-polling solutions that were used to simulate a full-duplex connection by maintaining two connections.
HTML5 WebSocket說明書定義了一個API,它允許網頁使用WebSocket協議與遠程主機進行全雙工通訊。它引進了WebSocket接口並定義了一個在網站之上使用一個Socket進行全雙工通訊的通道。與通過維護兩個連接而模擬全雙工連接的不能擴展的輪詢和長輪詢方式相比,HTML5 WebSockets大量減少了非必要的網絡傳輸和網絡延遲。

HTML5 WebSockets account for network hazards such as proxies and firewalls, making streaming possible over any connection, and with the ability to support upstream and downstream communications over a single connection, HTML5 WebSockets-based applications place less burden on servers, allowing existing machines to support more concurrent connections. The following figure shows a basic WebSocket-based architecture in which browsers use a WebSocket connection for full-duplex, direct communication with remote hosts.

HTML5 WebSockets在各種網絡障礙下,例如代理和防火牆,可以在任何連接上流轉,擁有在一個單獨的連接上進行上行下行通訊的能力,所以基於HTML5 WebSockets的應用會對服務器造成更小的負擔,在已存在的設備上能支持更多的併發連接


HTML5 WebSockets Architecture

One of the more unique features WebSockets provide is its ability to traverse firewalls and proxies, a problem area for many applications. Comet-style applications typically employ long-polling as a rudimentary line of defense against firewalls and proxies. The technique is effective, but is not well suited for applications that have sub-500 millisecond latency or high throughput requirements. Plugin-based technologies such as Adobe Flash, also provide some level of socket support, but have long been burdened with the very proxy and firewall traversal problems that WebSockets now resolve.

WebSockets提供的衆多特性之一是它能夠穿透防火牆和代理,解決了很多軟件的一個問題領域。Comet類型的軟件採用長連接作爲防衛防火牆和代理的基線。這種技術是有效的,但是不太適合那些要求500毫秒以內延遲或高吞吐量的應用。插件式的技術例如Adobe Flash,也提供了一些Socket級別的支持,但是也被代理和防火牆穿透問題所拖累,而這個問題WebSocket現在已經解決。

A WebSocket detects the presence of a proxy server and automatically sets up a tunnel to pass through the proxy. The tunnel is established by issuing an HTTP CONNECT statement to the proxy server, which requests for the proxy server to open a TCP/IP connection to a specific host and port. Once the tunnel is set up, communication can flow unimpeded through the proxy. Since HTTP/S works in a similar fashion, secure WebSockets over SSL can leverage the same HTTP CONNECT technique. Note that WebSockets are just beginning to be supported by modern browsers (Chrome now supports WebSockets natively). However, backward-compatible implementations that enable today's browsers to take advantage of this emerging technology are available.

一個WebSocket請求探測一個存在的代理服務器,並且自動設置一個通道穿過代理服務器。這個通道被建立是通過分配一個HTTP 連接句柄連接到代理服務器,對於代理服務器需要做的是針對某個主機和端口打開一個TCP/IP連接。一旦通道設置好,通信能夠暢通無阻通過代理服務器。因爲HTTPSHTTP工作原理相似,在SSL上的安全WebSockets 能夠利用相同的HTTP連接技術。必須注意WebSockets只被現代瀏覽器支持(Chrome一開始就支持WebSockets)。雖然如此,向後兼容性的實現使得當今的瀏覽器利用新興技術成爲可能。

WebSockets—like other pieces of the HTML5 effort such as Local Storage and Geolocation—was originally part of the HTML5 specification, but was moved to a separate standards document to keep the specification focused. WebSockets has been submitted to the Internet Engineering Task Force (IETF) by its creators, the Web Hypertext Application Technology Working Group (WHATWG). Authors, evangelists, and companies involved in the standardization still refer to the original set of features, including WebSockets, as "HTML5."

WebSockets-就像HTML5成就中的其他部分(例如本地存儲和地理位置)--HTML5規範的原始定義的一部分,但是爲了讓規範更加矚目,而被轉移到一個單獨標準文檔。WebSockets 已經被作者(超文本應用技術工作組,WHATWG)提交到互聯網工程任務組(IETF)。參與標準化的各個作者,傳播者和公司仍然關注一系列原始的特點

The WebSocket Protocol

The WebSocket protocol was designed to work well with the existing Web infrastructure. As part of this design principle, the protocol specification defines that the WebSocket connection starts its life as an HTTP connection, guaranteeing full backwards compatibility with the pre-WebSocket world. The protocol switch from HTTP to WebSocket is referred to as a the WebSocket handshake.

WebSocket 協議設計成能夠很好工作在現有的網絡基礎設施上。作爲設計原理的一部分,協議說明書定義了WebSocket 連接同HTTP連接一樣開使它的生命週期,和之前的WebSocket保持很好的向後兼容性。這個協議實現從HTTP協議轉到WebSocket協議的過程被稱爲WebSocket握手

The browser sends a request to the server, indicating that it wants to switch protocols from HTTP to WebSocket. The client expresses its desire through the Upgrade header:

瀏覽器發送一個請求到服務器,表示它想把HTTP協議轉爲WebSocket。客戶端通過更新頭字段(Upgrade header)實現了這個目的:

GET ws://echo.websocket.org/?encoding=text HTTP/1.1 Origin: http://websocket.org Cookie: __utma=99as Connection: Upgrade Host: echo.websocket.org Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw== Upgrade: websocket Sec-WebSocket-Version: 13 

If the server understands the WebSocket protocol, it agrees to the protocol switch through the Upgrade header.

如果服務器識別WebSocket協議,它通過Upgrade header接受協議轉換。

HTTP/1.1 101 WebSocket Protocol Handshake Date: Fri, 10 Feb 2012 17:38:18 GMT Connection: Upgrade Server: Kaazing Gateway Upgrade: WebSocket Access-Control-Allow-Origin: http://websocket.org Access-Control-Allow-Credentials: true Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU= Access-Control-Allow-Headers: content-type 

At this point the HTTP connection breaks down and is replaced by the WebSocket connection over the same underlying TCP/IP connection. The WebSocket connection uses the same ports as HTTP (80) and HTTPS (443), by default.

這時HTTP連接會分解,取而代之的是基於TCP/IP連接的WebSocket連接。WebSockets連接默認使用和HTTP(80)或者HTTPS(443)一樣的端口。

Once established, WebSocket data frames can be sent back and forth between the client and the server in full-duplex mode. Both text and binary frames can be sent in either direction at the same time. The data is minimally framed with just two bytes. In the case of text frames, each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between. WebSocket text frames use a terminator, while binary frames use a length prefix.

一旦連接建立,WebSocket數據幀能夠在客戶端與服務端以全雙工的模式來回發送。無論是文本還是二進制幀都可以在同一時間在任何方向發送。最小的幀的數據量僅爲2字節。若是文本幀的話,每一幀都是以0x00字節開頭,以0xFF字節結尾,中間是UTF-8數據。WebSocket文本幀使用終止符,而二進制幀使用的是長度前綴:

WebSocket Frame

Using the HTML5 WebSocket API

With the introduction of one succinct interface (see the following listing), developers can replace techniques such as long-polling and "forever frames," and as a result further reduce latency.

通過簡潔接口的介紹,開發者可以替換長輪詢和“永久幀forever frames”的技術,從而能更多的減少延遲。

[Constructor(in DOMString url, optional in DOMString protocol)] interface WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount;  // networking attribute Function onopen; attribute Function onmessage; attribute Function onclose; boolean send(in DOMString data); void close(); }; WebSocket implements EventTarget;

Utilizing the WebSocket interface couldn't be simpler. To connect to an end-point, just create a new WebSocket instance, providing the new object with a URL that represents the end-point to which you wish to connect, as shown in the following example. Note that a ws:// and wss:// prefix are proposed to indicate a WebSocket and a secure WebSocket connection, respectively.

使用WebSocket接口不能再簡單了。去連接一個終端,只需要創建一個WebSocket 實例,給這個實例提供一個代表你打算連接的終端的URL,如下面的例子所示。注意ws:// 和 wss://前綴分別代表WebSocket和安全的WebSocket連接。

var myWebSocket = new WebSocket("ws://www.websockets.org"); 

A WebSocket connection is established by upgrading from the HTTP protocol to the WebSockets protocol during the initial handshake between the client and the server. The connection itself is exposed via the "onmessage" and "send" functions defined by the WebSocket interface.

WebSocket連接的建立是以HTTP協議向WebSockets協議升級的方式完成的,發生在客戶端和服務端初次握手的時候。連接本身通過WebSocket接口中定義的"onmessage" 和 "send" 方法訪問。

Before connecting to an end-point and sending a message, you can associate a series of event listeners to handle each phase of the connection life-cycle as shown in the following example.

在連接到一個終端發送消息前,你可以設置一些列的事件監聽器去處理連接生命週期中的每一個階段。

myWebSocket.onopen = function(evt) { alert("Connection open ..."); }; myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); }; myWebSocket.onclose = function(evt) { alert("Connection closed."); }; 

To send a message to the server, simply call "send" and provide the content you wish to deliver. After sending the message, call "close" to terminate the connection, as shown in the following example. As you can see, it really couldn't be much easier.

向服務端發送一個消息,一般調用“send”並提供要發送的內容。發送完數據後,調用“close”去關閉連接。就像你看到的,它真的不能再簡單了。

myWebSocket.send("Hello WebSockets!"); myWebSocket.close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章