The WebSocket API

Internet Explorer 10 and Windows Store apps using JavaScript add support for the WebSocket API as defined in the World Wide Web Consortium (W3C)'s WebSocket API specification. WebSockets technology provides a new W3C JavaScript API and protocol for two-way communication over the Internet. This new protocol makes it easier to work directly with fixed data formats, and it bypasses the slower document-based HTTP protocol.

The current HTTP standard protocol is slow because it must request documents from a server and wait for the document to be sent before it can display a webpage. With WebSockets, you can send and receive your data immediately using text, binary arrays, or blobs.

The WebSocket API is simple and uncomplicated, requiring very little code. You can easily take advantage of low-latency bidirectional data interchanges that will help you create faster online games, instant social network notifications, real-time displays of stock and weather information, and other timely data.

Implementing WebSockets

Implementing this new data interchange technology is simple if you follow these steps:

1. Use a client browser that implements the WebSocket protocol.
2. Write code in a webpage that creates a client websocket.
3. Write code on a web server that responds to a client request through a websocket.

Use a WebSocket client

Internet Explorer 10 implements the WebSocket protocol, as do other major browsers. You can see the current state of browser support at the caniuse.com website.

The WebSocket protocol as defined in IETF tools website uses the following new URL schemes.


ws://
wss://

Write WebSocket client code

Your webpage code must do the following:

1. Initialize the websocket and connect to the server.
2. Test to see whether it was successful.
3. Send and receive data.

The following code shows typical code for defining the websocket URL:


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

The following code shows how to connect to a websocket and then test to see whether it was successful.


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


The previous code assumes you have serverStatus, destination, serverResponse, textmessage, and serverData as elements with IDs in your webpage. The result of the catch will be displayed in the console window if F12 developer tools is running. To send text message data, use the following type of code.


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

The previous code example assumes that you have the message text you want to send in a msgText element that includes ID in your webpage. Similarly, you can use the onmessage event to detect new messages or send a message to the server by using the send method. The send method can be used to send text, binary arrays, or blob data.

Write WebSocket server code

Server code that handles sockets can be written in any server language. Whatever language you choose, you must write code that accepts WebSocket requests and processes them appropriately.

WebSocket programming

WebSocket provides a set of objects, methods, and properties that you can use for WebSocket programming.

NameTypeDescription
WebSocket objectProvides bidirectional channel to remote host.
close methodCloses a websocket.
send methodSends data to a server using a websocket.
binaryType propertyBinary data format received by onmessage.
bufferedAmount propertyNumber of data bytes queued using send.
extensions propertyReports the extensions that the server selected.
onclose propertyEvent handler called when the socket is closed.
onerror propertyEvent handler called when there is an error.
onmessage propertyEvent handler to notify that a message is received.
onopen propertyEvent handler called if the websocket connected.
protocol propertyReports the protocol the server selected.
readyState propertyReports the state of the websocket connection.
url propertyReports the current URL of the socket.

 

API Reference

WebSocket API

IEBlog posts

WebSockets in Windows
Site Ready WebSockets

Specification

The WebSocket API

Related topics

Building real-time Web apps with HTML5 WebSockets
Building real-time Web apps with WebSockets using IIS, ASP.NET and WCF
Building Windows runtime sockets apps
Getting started with WebSockets in the Windows 8
Getting to know System.Net.WebSockets: A simple ASP.NET echo server
WebSockets: Stable and Ready for Developers

 

 

Show:
© 2015 Microsoft