📜 ⬆️ ⬇️

WebSockets in Windows 8 Consumer Preview

In Windows 8 CP and Server Beta, all Microsoft WebSocket clients and servers, including IE10, now support the final version of the IETF WebSocket protocol. In addition, IE10 implements the W3C WebSockets API preliminary recommendation.

WebSockets are stable and ready for developers to start creating innovative applications and services. This article is a simple introduction to the W3C WebSockets API and the WebSocket protocol located below. The updated Flipbook demonstration uses the latest API and protocol versions.

In my previous article, I described scripts for using WebSockets:
WebSockets allow Web applications to deliver notifications and updates in real time, directly to the browser. The developers faced problems associated with the need to bypass the limitations of the HTTP-based request-response type personal interaction model whose design is not intended for real-time scenarios. WebSockets allow browsers to open a two-way, full-duplex communication channel with server-side services. Each party can use this channel to immediately deliver data to the other party. Today, websites ranging from social networks and games to financial sites can provide better real-time scenarios than before, ideally using the same markup in different browsers.

Since the publication of that article in September 2011, working groups have made important progress. The WebSocket protocol has now become the standard protocol proposed by the IETF. In addition, the W3C WebSockets API is now a W3C recommendation candidate.
')

Introducing the WebSocket API with the Echo example


The code snippets below use a simple echo server created using the ASP.NET System.Web.WebSockets namespace to return text and binary messages that were sent from the application. The application allows the user to either enter the text that is to be sent, and displays the received response as a text message, or draw an image that can be sent to the server, and received back as a binary message.
image
A more complex example that allows you to experiment with the difference in delays and performance between WebSockets and HTTP polling can be seen in the Flipbook demonstration .

Details of the connection to the WebSocket server.


This simple explanation involves a direct connection between the application and the server. If a connection through a proxy is configured, IE10 starts the connection process by sending an HTTP CONNECT request to the proxy.

When a WebSocket object is created, a handshake is made between the client and the server that forms the WebSocket connection.
image

IE10 begins the handshake process by sending an 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 begins with a standard HTTP GET request, which allows the request to pass through firewalls, proxies, and other intermediate points:
  GET / echo HTTP / 1.1
 Host: example.microsoft.com 

The Upgrade HTTP header is a request to the server to switch the application-level protocol from HTTP to WebSocket.
  Upgrade: websocket
 Connection: Upgrade 

The server transforms the value of the Sec-WebSocket-Key header when responding to demonstrate that it understands the WebSocket protocol:
  Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ == 

The Origin header is configured by IE10 to allow the server to apply a source-based security policy .
  Origin: http://microsoft.com 

The Sec-WebSocket-Version header identifies the requested protocol version. Version 13 is final in the standard proposed by the IETF:
  Sec-WebSocket-Version: 13 

If the server accepts a request to update the application-level protocol, it returns an HTTP 101 Switching Protocols response:
image
  HTTP / 1.1 101 Switching Protocols
 Upgrade: websocket
 Connection: Upgrade 

To demonstrate that it really understands the WebSocket protocol, the server performs standardized conversion of the Sec-WebSocket-Key header value from a client request, and returns the result in the Sec-WebSocket-Accept header:
  Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK + xOo = 

IE10 then correlates the Sec-WebSocket-Key value to the Sec-WebSocket-Accept value to ensure that the server is really a WebSocket server, and not something else.

The client handshake forms an HTTP connection over TCP between IE10 and the server. After the server returns response 101, the application-level protocol switches from HTTP to WebSockets, which uses a previously established TCP connection.

HTTP completely disappears in the interaction picture after this switch. Messages can now be sent or received by both sides of the connection at any time, using the lightweight WebSocket protocol.
image

Programming the connection to the WebSocket server


The WebSocket protocol defines two new URI schemes that are very similar to HTTP schemes.



In the case of a proxy or other intermediate agents, the success of protected connections is more likely, since intermediate agents are less likely to interfere with protected traffic.

The following code snippet establishes a WebSocket connection:
var host = "ws://example.microsoft.com"; var socket = new WebSocket(host); 


ReadyState - Ready ... Install ... Let's Go ...

The WebSocket.readyState attribute provides the connection status: CONNECTING, OPEN, CLOSING, or CLOSED. When the WebSocket is just created, readyState is set to CONNECTING. When the connection is established successfully, the readyState is set to OPEN. If the connection failed to establish, readyState is set to CLOSED.

Subscribe to connection open events

To be notified that a connection has been created, the application must subscribe to open events.
 socket.onopen = function (openEvent) { document.getElementById("serverStatus").innerHTML = 'Web Socket State::' + 'OPEN'; }; 


Details behind the scenes: sending and receiving messages


After a successful handshake, the application and server can exchange WebSocket messages. A message is formed as a sequence of one or several message fragments (in other words, data “frames”).

Each frame includes such information as:

image
IE10 merges frames into a whole message before passing it to the script.

Programming sending and sending messages


The send API allows you to send messages to the server as UTF-8 encoded text, as well as ArrayBuffers or Blobs.

For example, this piece of code takes the text entered by the user and sends it to the server as a text message (UTF-8), which is then returned. This code verifies that Websocket.readyState is in the OPEN state:
 function sendTextMessage() { if (socket.readyState !== WebSocket.OPEN) { return; } var e = document.getElementById("textmessage"); socket.send(e.value); } 

This code receives the image drawn by the user on the 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()); // ... } 


Subscribe to event messages


To receive messages, the application must subscribe to event messages. The event handler receives a MessageEvent, which contains the data in MessageEvent.data. Data can be received as text or as binary messages.

When a binary message is received, the WebSocket.binaryType attribute controls what kind of data is returned, either as a Blob or as an ArrayBuffer. The attribute can be set either in “blob” or in “arraybuffer”.

The examples below use a default value of "blob".

This piece of code takes an image or text from a websocket server. If the data is binary, it receives an image and draws it on the target canvas. Otherwise, it receives the text in UTF-8 encoding and displays it in the 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; } }; 


Learn more about closing WebSocket connections.


Like a welcome handshake, there is also a farewell handshake. Any party (application or server) can initiate this process.

A special frame type (closing frame) is sent to the other side. The closing frame may contain an optional status code and reason for closing. The protocol defines several corresponding values ​​for the status code. The sender of the closing frame must no longer send any data after the closing frame.

When the other side receives a closing frame, it responds with its own closing frame. She can pre-send a few messages to the closing frame.
image

Programming WebSocket closing and subscribing to closing events


The application initiates a farewell handshake on an open connection using the close API:
 socket.close(1000, "normal close"); 


To receive notifications about a connection being closed, the application must subscribe to connection closure events.
 socket.onclose = function (closeEvent) { document.getElementById("serverStatus").innerHTML = 'Web Socket State::' + 'CLOSED'; }; 


close The API accepts two optional parameters: a status code from the list defined in the protocol, and a description. The status code must either be 1000 or be in the range from 3000 to 4999. When the connection is closed, the readyState attribute is set to CLOSING. After IE10 receives the response with the closing frame from the server, the readyState attribute is set to CLOSED and a close event is generated.

Use Fiddler to view WebSockets traffic


Fiddler is a popular HTTP debugging proxy. In its latest version, there is some support for the WebSocket protocol. You can learn the header exchange in the WebSocket handshake:
image

All WebSocket messages are also logged. Below in the screenshot you can see how the application «spiral» sends a text message to the server, which sends it back:
image

Conclusion


If you want to learn more about WebSockets, you can view these sessions from the Microsoft conference // Build /, held in September 2011:

If you are unfamiliar with Microsoft technology for creating WebSocket services, these articles can be a good guide:


I hope that you will start developing on the basis of WebSockets today, and share with us your impressions.

—Brian Raymor, Senior Program Manager, Windows Networking

Source: https://habr.com/ru/post/141384/


All Articles