WCF WebSockets: First Glance

I finally got around to playing with the first drop of WebSockets support for WCF. I’m pretty familiar with WebSockets as I’ve been using Node.js to play around with them for quite a while now. The server API in Node.js is wonderful as it couldn’t be simpler – to demonstrate this, take a look at how we’d create a basic echo server.

var ws = require("websocket-server");

var server = ws.createServer();

server.addListener("connection", function(connection){
  connection.addListener("message", function(msg){
    server.send(msg);
  });
});

server.listen(8080);

When I heard that Microsoft was planning on integrating WebSockets into WCF my first thoughts weren’t all that positive. Now I know it’s not quite the case since .NET 4, but WCF has had a reputation for rather large complex API’s and heaps of XML. I was dreading what a WCF take on the above would look like. Turns out, perhaps I should be a little more optimistic.

class Program
{
    static void Main(string[] args)
    {
        var host = new WebSocketsHost(new Uri("ws://localhost:4502/echo"));
        host.AddWebSocketsEndpoint();
        host.Open();
        Console.ReadKey(true);
        host.Close();
    }
}

public class EchoService : WebSocketsService
{
    public override void OnMessage(JsonValue jsonValue)
    {
        Send(jsonValue);
    }
}

That’s really the kind of simplicity I was really hoping to see. Now the interesting question is how it’s going to look when dealing with multiple clients. Node kind of has an advantage here as it’s entirely single threaded (yeah, I said advantage), but with .NET’s recent concurrent collections and a rather nice API for dealing with events (Rx) I’m feeling pretty hopeful.