关闭

websocket

1675人阅读 评论(0) 收藏 举报
分类:

IIS 8.0 WebSocket Protocol Support

By Microsoft

November 28, 2012

Compatibility

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.

Contents

Problem

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.

Solution

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 RFC 6455, 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:

Step by Step Instructions

To enable support for the WebSocket Protocol on Windows Server 2012, use the following steps:

  1. Open Server Manager.
  2. Under the Manage menu, click Add Roles and Features.
  3. Select Role-based or Feature-based Installation, and then click Next.
  4. Select the appropriate server, (your local server is selected by default), and then click Next.
  5. Expand Web Server (IIS) in the Roles tree, then expand Web Server, and then expand Application Development.
  6. Select WebSocket Protocol, and then click Next.
  7. If no additional features are needed, click Next.
  8. Click Install.
  9. When the installation completes, click Close to exit the wizard.

Summary

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:

 
WebSocket API

Internet Explorer 10 和使用 JavaScript 的 Windows 应用商店应用引入了对 WebSocket API 的支持,其定义位于万维网联盟 (W3C) 的 WebSocket API 规范中。WebSockets 技术为通过 Internet 进行的双向通信提供了一个新的 W3C JavaScript API 和协议。这个新协议更便于直接处理固定数据格式,它会绕过速度较慢的基于文档的 HTTP 协议。

当前的 HTTP 标准协议很慢,因为它必须从服务器请求文档而且必须等待该文档发送,才能显示网页。使用 WebSocket,你可以使用文本、二进制数组或 BLOB 立即发送和接收你的数据。

WebSocket API 非常简单,它只需非常少的代码。你可以方便地利用低延迟双向数据交换,从而有助于快速创建在线游戏、即时社交网络通知、实时显示股市和天气信息,以及其他实时数据。

实现 WebSocket

如果你按照下列步骤进行操作,则实现此数据交换新技术将非常简单:

1. 使用一个客户端浏览器来实现 WebSocket 协议。
2. 在网页中编写代码来创建客户端 Websocket。
3. 在 Web 服务器上编写代码来通过 Websocket 响应客户端请求。

使用 WebSocket 客户端

Internet Explorer 10 实现 WebSocket 协议,如同其他主流浏览器的行为。你可在 caniuse.com 网站上看到浏览器支持的当前状态。

IETF 工具网站中指定的 WebSocket 协议使用以下新的 URL 方案。

  1. ws://
  2. wss://

编写 WebSocket 客户端代码

你的网页代码必须执行以下操作:

1. 初始化 websocket 并连接到服务器。
2. 测试以查看它是否成功。
3. 发送和接收数据。

以下代码显示了指定 websocket URL 的典型代码:

  1. var host = 'ws://example.microsoft.com';

以下代码显示了如何连接到 websocket 并测试以查看它是否成功。

  1.  var host = "ws://sample-host/echo";
  2.  try {
  3.     socket = new WebSocket(host);
  4.  
  5.     socket.onopen = function (openEvent) {
  6.        document.getElementById("serverStatus").innerHTML = 
  7.           'WebSocket Status:: Socket Open';
  8.     };
  9.  
  10.  socket.onmessage = function (messageEvent) {
  11.  
  12.     if (messageEvent.data instanceof Blob) {
  13.     var destinationCanvas = document.getElementById('destination');
  14.     var destinationContext = destinationCanvas.getContext('2d');
  15.     var image = new Image();
  16.     image.onload = function () {
  17.        destinationContext.clearRect(00
  18.           destinationCanvas.width, destinationCanvas.height);
  19.        destinationContext.drawImage(image, 00);
  20.     }
  21.     image.src = URL.createObjectURL(messageEvent.data);
  22.  } else {
  23.     document.getElementById("serverResponse").innerHTML = 
  24.        'Server Reply:: ' + messageEvent.data;
  25.     }
  26.  };
  27.  
  28.  socket.onerror = function (errorEvent) {
  29.     document.getElementById("serverStatus").innerHTML = 
  30.       'WebSocket Status:: Error was reported';
  31.     };
  32.  
  33.  socket.onclose = function (closeEvent) {
  34.     document.getElementById("serverStatus").innerHTML = 
  35.       'WebSocket Status:: Socket Closed';
  36.     };
  37.  }
  38.   catch (exception) { if (window.console) console.log(exception); }
  39.  }
  40.  
  41.  function sendTextMessage() {
  42.  
  43.     if (socket.readyState != WebSocket.OPEN) return;
  44.  
  45.     var e = document.getElementById("textmessage");
  46.     socket.send(e.value);
  47.  }
  48.  
  49.  function sendBinaryMessage() {
  50.     if (socket.readyState != WebSocket.OPEN) return;
  51.  
  52.     var sourceCanvas = document.getElementById('source');
  53.  
  54.     socket.send(sourceCanvas.msToBlob());
  55.  }    

前面的代码假设你有 serverStatus、destination、serverResponse、textmessage 和 serverData作为你的网页中带 ID 的元素。如果 F12 开发人员工具正在运行,捕获结果将显示在控制台窗口中。要发送文本消息数据,请使用以下类型的代码。

  1. var e = document.getElementById("msgText");
  2. socket.send(e.value);

上面的代码示例假设你有要使用网页中带 ID 的 msgText 元素发送的消息文本。同样,你可以使用 onmessage 事件检测新消息或使用 send 方法发送消息到服务器。send 方法可用于发送文本、二进制数组或 Blob 数据。

编写 WebSocket 服务器代码

处理套接字的服务器代码能够以任何服务器语言编写。无论你选择哪种语言,都必须编写代码以接受 WebSocket 请求并相应地处理它们。

WebSocket 编程

WebSocket 提供一组可用于 WebSocket 编程的对象、方法和属性。

名称 类型 描述
WebSocket 对象 提供到远程主机的双向通道。
close 方法 关闭 websocket。
send 方法 使用 websocket 发送数据到服务器。
binaryType 属性 onmessage 接收的二进制数据格式。
bufferedAmount 属性 使用 send 的已排队的数据字节数。
extensions 属性 报告服务器所选中的扩展名。
onclose 属性 当套接字关闭时调用的事件处理程序。
onerror 属性 当出现错误时调用的事件处理程序。
onmessage 属性 通知接收到消息的事件处理程序。
onopen 属性 当 websocket 已连接时调用的事件处理程序。
protocol 属性 报告服务器所选中的协议。
readyState 属性 报告 websocket 连接的状态。
url 属性 报告套接字的当前 URL。

 

API 参考

WebSocket API

IEBlog 文章

Windows Consumer Preview 中的 WebSocket
支持站点的 WebSocket

规范

WebSocket API

相关主题

使用 HTML5 WebSocket 构建实时 Web 应用
通过使用 IIS、ASP.NET 和 WCF 的 WebSocket 构建实时 Web 应用
构建 Windows 运行时套接字应用
Windows 8 中的 WebSocket 入门
了解 System.Net.WebSocket:简单的 ASP.NET 回显服务器
WebSocket:稳定可靠,随时可供开发人员使用

WebSockets: Stable and Ready for Developers

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 W3CWebSocket API and its underlyingWebSocket protocol. The updatedFlipbook demo uses the latest version of the API and protocol.

Working groups have made significant progress and the WebSocket API is a W3C Candidate Recommendation. Internet Explorer 10 implements this version of the spec.  You can learn about the evolution of the spechere

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.

Introduction to the WebSocket API Using an Echo Example

The code snippets below use a simple echo server created with ASP.NET’s System.Web.WebSockets 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 theFlipbook demo.

Details of Connecting to a WebSocket Server

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:

  1. GET /echo HTTP/1.1
  2. Host: example.microsoft.com
  3. Upgrade: websocket
  4. Connection: Upgrade
  5. Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
  6. Origin: http://microsoft.com
  7. 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:

  1. GET /echo HTTP/1.1
  2. Host: example.microsoft.com

The HTTP Upgrade header requests that the server switch the application-layer protocol from HTTP to the WebSocket protocol.

  1. Upgrade: websocket
  2. Connection: Upgrade

The server transforms the value in the Sec-WebSocket-Key header in its response to demonstrate that it understands the WebSocket protocol:

  1. Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

The Origin header is set by IE10 to allow the server to enforce origin-based security.

  1. 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:

  1. Sec-WebSocket-Version: 13

If the server accepts the request to upgrade the application-layer protocol, it returns aHTTP 101 Switching Protocols response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: 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:

  1. 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.

Programming Connecting to a WebSocket Server

The WebSocket protocol defines two new URI schemes which are similar to the HTTP schemes.

  • "ws:" "//" host [ ":" port ] path [ "?" query ] is modeled on the “http:” scheme. Its default port is 80. It is used for unsecure (unencrypted) connections.
  • "wss:" "//" host [ ":" port ] path [ "?" query ] is modeled on the “https:” scheme. Its default port is 443. It is used for secure connections tunneled overTransport Layer Security.

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:

  1. var host = "ws://example.microsoft.com";
  2. var socket = new WebSocket(host);

ReadyState – Ready … Set … Go …

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.

Registering for Open Events

To receive notifications when the connection has been created, the application must register for open events.

  1. socket.onopen = function (openEvent) {
  2. document.getElementById("serverStatus").innerHTML = 'Web Socket State::' + 'OPEN';
  3. };

Details Behind Sending and Receiving Messages

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:

  • Frame length
  • Type of message (binary or text) in the first frame in the message
  • A flag (FIN) indicating whether this is the last frame in the message

IE10 reassembles the frames into a complete message before passing it to the script.

Programming Sending and Receiving Messages

The send API allows applications to send messages to a Websocket server as UTF-8 text,ArrayBuffers, 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:

  1. function sendTextMessage() {
  2. if (socket.readyState != WebSocket.OPEN)
  3. return;
  4. var e = document.getElementById("textmessage");
  5. socket.send(e.value);
  6. }

This snippet retrieves the image drawn by the user in a canvas and sends it to the server as a binary message:

  1. function sendBinaryMessage() {
  2. if (socket.readyState != WebSocket.OPEN)
  3. return;
  4. var sourceCanvas = document.getElementById('source');
  5. // msToBlob returns a blob object from a canvas image or drawing
  6. socket.send(sourceCanvas.msToBlob());
  7. // ...
  8. }

Registering for Message Events

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.

  1. socket.onmessage = function (messageEvent) {
  2. if (messageEvent.data instanceof Blob) {
  3. var destinationCanvas = document.getElementById('destination');
  4. var destinationContext = destinationCanvas.getContext('2d');
  5. var image = new Image();
  6. image.onload = function () {
  7. destinationContext.clearRect(0, 0, destinationCanvas.width, destinationCanvas.height);
  8. destinationContext.drawImage(image, 0, 0);
  9. }
  10. image.src = URL.createObjectURL(messageEvent.data);
  11. } else {
  12. document.getElementById("textresponse").value = messageEvent.data;
  13. }
  14. };

Details of Closing a WebSocket Connection

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 appropriatevalues 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.

Programming Closing a WebSocket and Registering for Close Events

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.

  1. socket.onclose = function (closeEvent) {
  2. document.getElementById("serverStatus").innerHTML = 'Web Socket State::' + 'CLOSED';
  3. };

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.

Using Fiddler to See WebSockets Traffic

Fiddler 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:

Conclusion

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!

About the Author

Brian Raymor is a Senior Program Manager in the Windows Networking group at Microsoft.

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:506117次
    • 积分:5838
    • 等级:
    • 排名:第4567名
    • 原创:20篇
    • 转载:398篇
    • 译文:0篇
    • 评论:29条
    最新评论