Friday 14 October 2011

Getting to know System.Net.WebSockets: A simple ASP.NET echo server

The WebSockets offering for .NET 4.5 consists of several APIs that vary in granularity and purpose. The new System.Net.WebSockets namespace contains a set of types that are used regardless of whether you are hosting your WebSocket server in ASP.NET or if you are using the low level HttpListener class (WCF uses HttpListener when it needs to handle HTTP traffic in self-hosted mode). The goal of this set of types is to define a shared low-level WebSockets API that ASP.NET, WCF and .NET developers can build on top of.

System.Net.WebSockets is not to be confused with the new WinRT WebSocket APIs found in Windows.Networking.Sockets. The WinRT APIs provide client functionality only while the the System.Net.WebSockets types are designed for server side use.

The easiest way to get to know this new API is to look at a simple example. I’ve implemented a very basic WebSocket echo server in ASP.NET that demonstrates how to accept a WebSocket connection in ASP.NET, obtain an instance of System.Net.WebSockets.WebSocket and then begin send and receive operations using the methods on this type. Keep in mind that we do not expect most developers to use these low level APIs for every day applications – this is what our Microsoft.WebSockets NuGet package is for. Future posts will cover this package in more detail.

I’ve annotated the source code for this echo server and made it available in HTML format. Please check it out! Do you like samples presented in this style? Let me know in the comments.

If you want to download and run this example, it’s called AspNetWebSocketEcho and is part of my WebSocket Samples project on github. You will need to use the Windows 8 developer preview if you want to try this stuff out. See my earlier post for instructions on how to set up your development environment.