WebSockets – introduction

This is the first of a series of posts about building real-time applications for Windows 8 (metro style) using websockets. These are my notes for a session that I will be presenting at the Orlando Code Camp on March 16th.

So what are websockets? Websockets are relatively new technology that allows two-way communication between a client and a server. In the past if we wanted to simulate a two way communication between the client and the server we had to do some form of polling where the client asks the server “do you have something for me?” and then the server have the opportunity to send back it’s message. The problem with that model is that most of the times there is no message to be send and so 90% of the whole communication is complete waste. With websockets the only communication that occurs is when either the client or the server have the message for the other. This is a lot more effective, scales better and is a lot easier to program.

Websockets are often viewed as a part of the HTML5 standard but in fact both server and client development is fully supported with the version 4.5 of the .net framework on a Windows 8 machine or Windows Server 2012 using IIS 8. Also all current version of the major web browsers support websockets including IE10, Firefox 6, Chrome 14 and Opera 12.

How does it work? The client send an HTTP GET request to the server asking to open a websocket connection. The server replies with a special “connection upgrade” response and after that both the client and the server can send messages to each other in any order. (This is obviously the simplified version, look in the F12 dev tools in Chrome to see the exact format of the request and the response).

Rome was not build in a day. Let’s create a simple client and a server to demonstrate the mechanics of the websockets handshake and communication.

– Using Visual Studio 2012 on a Windows 8 machine with IIS8 installed create a new Web Application. Configure the app to use IIS instead of the development web server.

– Install nuget package Microsoft.WebSockets

– Add a new HttpHandler called WS.ahx – this will perform the handshake

using Microsoft.Web.WebSockets;

public class WS : IHttpHandler
    public bool IsReusable
        get { return false; }

    public void ProcessRequest(HttpContext context)
        if (context.IsWebSocketRequest)
            context.AcceptWebSocketRequest(new Server());

– Add a new class Server.cs that inherits from WebSocketHandler and overrides OnOpen(), OnMessage() and OnClose() methods

using Microsoft.Web.WebSockets;

public class Server : WebSocketHandler
    public override void OnOpen()
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        base.Send(serializer.Serialize("hello from server"));

    public override void OnMessage(string message)
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        base.Send(serializer.Serialize(message + " back"));

    public override void OnClose()

– And finally add a web page called default.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>WebSockets demo</title>
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.0.6-development-only.js"></script>
    <h1>WebSockets demo</h1>

    <input type="text" id="message" />
    <input type="button" id="send" value="Send" />

    <pre id="messages"></pre>

    <script type="text/javascript">

        $(function () {

            if (Modernizr.websockets) {
                log("### websockets supported");

            if (!window.WebSocket && window.MozWebSocket)
                window.WebSocket = window.MozWebSocket;

            var host = "ws://localhost:8080/WS.ashx";
            var connection = new WebSocket(host);

            connection.onopen = function () {
                log("### connection open");

            connection.onclose = function () {
                log("### connection closed");

            connection.onmessage = function (message) {
                var data = window.JSON.parse(message.data);
                log("<<< " + data);

            $("#send").click(function () {
                var message = $("#message").val();
                log(">>> " + message);

        function log(s) {


– Set the default.html to be a start page and run the application. A simple webpage should appear with a textbox and a button. Whatever we say to the server the server should say it back. Now we are in business…

One thought on “WebSockets – introduction

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s