本文共 15876 字,大约阅读时间需要 52 分钟。
By
November 28, 2012
Version | Notes |
---|---|
IIS 8.0 | The WebSocket Protocol was introduced in IIS 8.0. |
IIS 7.5 | The WebSocket Protocol was not supported in IIS 7.5. |
IIS 7.0 | The WebSocket Protocol was not supported in IIS 7.0. |
One of the limitations to HTTP is that it was designed as a one-directional method of communication. However, many modern web-based applications require more real-time, two-way communications in order to function optimally.
With the release of Windows Server 2012 and Windows 8, Internet Information Services (IIS) 8.0 has added support for the WebSocket Protocol.
The WebSocket Protocol is an open standard that is defined in , and developers can use this functionality to create applications that implement two-way communications over the Internet between a client and server. For more information about the WebSocket Protocol, see the following articles:
To enable support for the WebSocket Protocol on Windows Server 2012, use the following steps:
IIS 8.0 has added support for WebSocket Protocol, which enables dynamic, two-way communications over the Internet. Additional information can be found on the following URLs:
Internet Explorer 10 和使用 JavaScript 的 Windows 应用商店应用引入了对 WebSocket API 的支持,其定义位于万维网联盟 (W3C) 的 WebSocket API 规范中。WebSockets 技术为通过 Internet 进行的双向通信提供了一个新的 W3C JavaScript API 和协议。这个新协议更便于直接处理固定数据格式,它会绕过速度较慢的基于文档的 HTTP 协议。
当前的 HTTP 标准协议很慢,因为它必须从服务器请求文档而且必须等待该文档发送,才能显示网页。使用 WebSocket,你可以使用文本、二进制数组或 BLOB 立即发送和接收你的数据。
WebSocket API 非常简单,它只需非常少的代码。你可以方便地利用低延迟双向数据交换,从而有助于快速创建在线游戏、即时社交网络通知、实时显示股市和天气信息,以及其他实时数据。
如果你按照下列步骤进行操作,则实现此数据交换新技术将非常简单:
Internet Explorer 10 实现 WebSocket 协议,如同其他主流浏览器的行为。你可在 网站上看到浏览器支持的当前状态。
在 网站中指定的 WebSocket 协议使用以下新的 URL 方案。
ws:// wss://
你的网页代码必须执行以下操作:
以下代码显示了指定 websocket URL 的典型代码:
var host = 'ws://example.microsoft.com';
以下代码显示了如何连接到 websocket 并测试以查看它是否成功。
var host = "ws://sample-host/echo"; try { socket = new WebSocket(host); socket.onopen = function (openEvent) { document.getElementById("serverStatus").innerHTML = 'WebSocket Status:: Socket Open'; }; socket.onmessage = function (messageEvent) { if (messageEvent.data instanceof Blob) { var destinationCanvas = document.getElementById('destination'); var destinationContext = destinationCanvas.getContext('2d'); var image = new Image(); image.onload = function () { destinationContext.clearRect(0, 0, destinationCanvas.width, destinationCanvas.height); destinationContext.drawImage(image, 0, 0); } image.src = URL.createObjectURL(messageEvent.data); } else { document.getElementById("serverResponse").innerHTML = 'Server Reply:: ' + messageEvent.data; } }; socket.onerror = function (errorEvent) { document.getElementById("serverStatus").innerHTML = 'WebSocket Status:: Error was reported'; }; socket.onclose = function (closeEvent) { document.getElementById("serverStatus").innerHTML = 'WebSocket Status:: Socket Closed'; }; } catch (exception) { if (window.console) console.log(exception); } } function sendTextMessage() { if (socket.readyState != WebSocket.OPEN) return; var e = document.getElementById("textmessage"); socket.send(e.value); } function sendBinaryMessage() { if (socket.readyState != WebSocket.OPEN) return; var sourceCanvas = document.getElementById('source'); socket.send(sourceCanvas.msToBlob()); }
前面的代码假设你有 serverStatus、destination、serverResponse、textmessage 和 serverData作为你的网页中带 ID 的元素。如果 F12 开发人员工具正在运行,捕获结果将显示在控制台窗口中。要发送文本消息数据,请使用以下类型的代码。
var e = document.getElementById("msgText"); socket.send(e.value);
上面的代码示例假设你有要使用网页中带 ID 的 msgText 元素发送的消息文本。同样,你可以使用 事件检测新消息或使用 send 方法发送消息到服务器。 方法可用于发送文本、二进制数组或 Blob 数据。
处理套接字的服务器代码能够以任何服务器语言编写。无论你选择哪种语言,都必须编写代码以接受 WebSocket 请求并相应地处理它们。
WebSocket 提供一组可用于 WebSocket 编程的对象、方法和属性。
名称 | 类型 | 描述 |
---|---|---|
对象 | 提供到远程主机的双向通道。 | |
方法 | 关闭 websocket。 | |
方法 | 使用 websocket 发送数据到服务器。 | |
属性 | 由 接收的二进制数据格式。 | |
属性 | 使用 send 的已排队的数据字节数。 | |
属性 | 报告服务器所选中的扩展名。 | |
属性 | 当套接字关闭时调用的事件处理程序。 | |
属性 | 当出现错误时调用的事件处理程序。 | |
属性 | 通知接收到消息的事件处理程序。 | |
属性 | 当 websocket 已连接时调用的事件处理程序。 | |
属性 | 报告服务器所选中的协议。 | |
属性 | 报告 websocket 连接的状态。 | |
属性 | 报告套接字的当前 URL。 |
By Brian Raymor
WebSockets are stable and ready for developers to start creating innovative applications and services. This tutorial provides a simple introduction to the W3C and its underlying. The updated uses the latest version of the API and protocol.
Working groups have made significant progress and the is a W3C Candidate Recommendation. implements this version of the spec. You can learn about the evolution of the spec.
WebSockets enable Web applications to deliver real-time notifications and updates in the browser. Developers have faced problems in working around the limitations in the browser’s original HTTP request-response model, which was not designed for real-time scenarios. WebSockets enable browsers to open a bidirectional, full-duplex communication channel with services. Each side can then use this channel to immediately send data to the other. Now, sites from social networking and games to financial sites can deliver better real-time scenarios, ideally using same markup across different browsers.
The code snippets below use a simple echo server created with ASP.NET’s namespace to echo back text and binary messages that are sent from the application. The application allows the user to type in text to be sent and echoed back as a text message or draw a picture that can be sent and echoed back as a binary message.
For a more complex example that allows you to experiment with latency and performance differences between WebSockets and HTTP polling, see the.
This simple explanation is based on a direct connection between the application and the server. If a proxy is configured, then IE10 starts the process by sending a HTTP CONNECT request to the proxy.
When a WebSocket object is created, a handshake is exchanged between the client and the server to establish the WebSocket connection.
IE10 starts the process by sending a HTTP request to the server:
GET /echo HTTP/1.1 Host: example.microsoft.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://microsoft.com Sec-WebSocket-Version: 13
Let’s look at each part of this request.
The connection process starts with a standard HTTP GET request which allows the request to traverse firewalls, proxies, and other intermediaries:
GET /echo HTTP/1.1 Host: example.microsoft.com
The HTTP requests that the server switch the application-layer protocol from HTTP to the WebSocket protocol.
Upgrade: websocket Connection: Upgrade
The server transforms the value in the Sec-WebSocket-Key header in its response to demonstrate that it understands the WebSocket protocol:
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
The Origin header is set by IE10 to allow the server to enforce .
Origin: http://microsoft.com
The Sec-WebSocket-Version header identifies the requested protocol version. Version 13 is the final version in the IETF proposed standard:
Sec-WebSocket-Version: 13
If the server accepts the request to upgrade the application-layer protocol, it returns a response:
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: Upgrade
To demonstrate that it understands the WebSocket Protocol, the server performs a standardized transformation on the Sec-WebSocket-Key from the client request and returns the results in the Sec-WebSocket-Accept header:
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
IE10 then compares Sec-WebSocket-Key with Sec-WebSocket-Accept to validate that the server is a WebSocket server and not a HTTP server with delusions of grandeur.
The client handshake established a HTTP-on-TCP connection between IE10 and server. After the server returns its 101 response, the application-layer protocol switches from HTTP to WebSockets which uses the previously established TCP connection.
HTTP is completely out of the picture at this point. Using the lightweight WebSocket wire protocol, messages can now be sent or received by either endpoint at any time.
The WebSocket protocol defines which are similar to the HTTP schemes.
When proxies or network intermediaries are present, there is a higher probability that secure connections will be successful, as intermediaries are less inclined to attempt to transform secure traffic.
The following code snippet establishes a WebSocket connection:
var host = "ws://example.microsoft.com"; var socket = new WebSocket(host);
The WebSocket.readyState attribute represents the state of the connection: CONNECTING, OPEN, CLOSING, or CLOSED. When the WebSocket is first created, the readyState is set to CONNECTING. When the connection is established, the readyState is set to OPEN. If the connection fails to be established, then the readyState is set to CLOSED.
To receive notifications when the connection has been created, the application must register for open events.
socket.onopen = function (openEvent) { document.getElementById("serverStatus").innerHTML = 'Web Socket State::' + 'OPEN'; };
After a successful handshake, the application and the Websocket server may exchange WebSocket messages. A message is composed as a sequence of one or more message fragments or data “frames.”
Each frame includes information such as:
IE10 reassembles the frames into a complete message before passing it to the script.
The send API allows applications to send messages to a Websocket server as UTF-8 text,, or Blobs.
For example, this snippet retrieves the text entered by the user and sends it to the server as a UTF-8 text message to be echoed back. It verifies that the Websocket is in an OPEN readyState:
function sendTextMessage() { if (socket.readyState != WebSocket.OPEN) return; var e = document.getElementById("textmessage"); socket.send(e.value); }
This snippet retrieves the image drawn by the user in a canvas and sends it to the server as a binary message:
function sendBinaryMessage() { if (socket.readyState != WebSocket.OPEN) return; var sourceCanvas = document.getElementById('source'); // msToBlob returns a blob object from a canvas image or drawing socket.send(sourceCanvas.msToBlob()); // ... }
To receive messages, the application must register for message events. The event handler receives a MessageEvent which contains the data in MessageEvent.data. Data can be received as text or binary messages.
When a binary message is received, the WebSocket.binaryType attribute controls whether the message data is returned as a Blob or an ArrayBuffer datatype. The attribute can be set to either “blob” or “arraybuffer.”
The examples below use the default value which is “blob.”
This snippet receives the echoed image or text from the websocket server. If the data is a Blob, then an image was returned and is drawn in the destination canvas; otherwise, a UTF-8 text message was returned and is displayed in a text field.
socket.onmessage = function (messageEvent) { if (messageEvent.data instanceof Blob) { var destinationCanvas = document.getElementById('destination'); var destinationContext = destinationCanvas.getContext('2d'); var image = new Image(); image.onload = function () { destinationContext.clearRect(0, 0, destinationCanvas.width, destinationCanvas.height); destinationContext.drawImage(image, 0, 0); } image.src = URL.createObjectURL(messageEvent.data); } else { document.getElementById("textresponse").value = messageEvent.data; } };
Similar to the opening handshake, there is a closing handshake. Either endpoint (the application or the server) can initiate this handshake.
A special kind of frame – a close frame – is sent to the other endpoint. The close frame may contain an optional status code and reason for the close. The protocol defines a set of appropriate for the status code. The sender of the close frame must not send further application data after the close frame.
When the other endpoint receives the close frame, it responds with its own close frame in response. It may send pending messages prior to responding with the close frame.
The application initiates the close handshake on an open connection with the close API:
socket.close(1000, "normal close");
To receive notifications when the connection has been closed, the application must register for close events.
socket.onclose = function (closeEvent) { document.getElementById("serverStatus").innerHTML = 'Web Socket State::' + 'CLOSED'; };
The close API accepts two optional parameters: a status code as defined by the protocol and a description. The status code must be either 1000 or in the range 3000 to 4999. When close is executed, the readyState attribute is set to CLOSING. After IE10 receives the close response from the server, the readyState attribute is set to CLOSED and a close event is fired.
is a popular HTTP debugging proxy. There is some support in the latest versions for the WebSocket protocol. You can inspect the headers exchanged in the WebSocket handshake:
All the WebSocket messages are also logged. In the screenshot below, you can see that “spiral” was sent to the server as a UTF-8 text message and echoed back:
If you want to learn more about WebSockets, you may watch these sessions from the Microsoft //Build/ conference from September 2011:
If you’re curious about using Microsoft technologies to create a WebSocket service, these posts are good introductions:
Start developing with WebSockets today!
Brian Raymor is a Senior Program Manager in the Windows Networking group at Microsoft.
转载地址:http://udhvi.baihongyu.com/