博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
websocket
阅读量:4139 次
发布时间:2019-05-25

本文共 15876 字,大约阅读时间需要 52 分钟。

IIS 8.0 WebSocket Protocol Support

By

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

  • WebSockets
  • WebSockets: Stable and Ready for Developers

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:

  • Getting started with WebSockets in Windows 8
  • IIS and Websockets
  • System.Net.WebSockets Namespace
 
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 协议,如同其他主流浏览器的行为。你可在 网站上看到浏览器支持的当前状态。

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

ws:// 
wss://

编写 WebSocket 客户端代码

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

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

以下代码显示了指定 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 编程的对象、方法和属性。

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

 

API 参考

IEBlog 文章

规范

相关主题

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

Introduction to the WebSocket API Using an Echo Example

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.

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:

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.

Programming Connecting to a WebSocket Server

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

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

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);

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.

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

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,, 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());
// ...
}

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.

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;
}
};

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

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.

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.

Using Fiddler to See WebSockets Traffic

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.

 

转载地址:http://udhvi.baihongyu.com/

你可能感兴趣的文章
配置文件的重要性------轻化操作
查看>>
cp后文件时间会变, mv后文件时间不会变化------定位一个低概率core问题时, 差点误导了自己
查看>>
又是缓存惹的祸!!!
查看>>
为什么要实现程序指令和程序数据的分离?
查看>>
我对C++ string和length方法的一个长期误解------从protobuf序列化说起(没处理好会引起数据丢失、反序列化失败哦!)
查看>>
一起来看看protobuf中容易引起bug的一个细节
查看>>
无protobuf协议情况下的反序列化------貌似无解, 其实有解!
查看>>
make -n(仅列出命令, 但不会执行)用于调试makefile
查看>>
make -k(keep going)命令会在发现错误时继续执行(用于一次发现所有错误)
查看>>
makefile中“-“符号的使用
查看>>
一个奇葩的编译错误和解决方案------error: expected identifier before numeric constant
查看>>
又一次遇到undefined reference to xxx
查看>>
再遇"\xff\xfe"
查看>>
共享内存linux C/C++代码实战------顺便玩下ipcs, ipcrm, shmget, shmat, shmdt, shmctl
查看>>
为什么你的共享内存key为0且无法删除?
查看>>
玩转消息队列之C/C++代码
查看>>
linux中的ethtool命令
查看>>
迟延分段与分片: Segmentation and Checksum Offloading: Turning Off with ethtool (好文)
查看>>
一同事出现了http 404错误
查看>>
一同事出现了http 500错误
查看>>