您的位置:首页 > Web前端 > HTML5

WebSocket官方文档翻译——About HTML5 WebSockets

2014-04-20 18:17 441 查看


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的应用会对服务器造成更小的负担,在已存在的设备上能支持更多的并发连接。



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连接。一旦通道设置好,通信能够畅通无阻通过代理服务器。因为HTTPS和HTTP工作原理相似,在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文本帧使用终止符,而二进制帧使用的是长度前缀:




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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: