A Sneak Preview of WebSocket-enabled WCF Services

December 25, 2010 | WCF

Recently the Interoperability Bridges and Labs Center (run by the Microsoft Interoperability Strategy Group) released a prototype  implementation (in managed code) of two drafts of the WebSockets protocol specification:

The prototype can be found at HTML5 Labs, however (at the time of this writing) the samples did not come with source code and they were delay signed (which means you have to follow the instructions to run them). After running the samples (and since I had no access to the source code) I opened with reflector and had a look under the hood.

What I noticed is that a WebSocket-enabled service in .NET will be written like any other WCF service with two differences:

The service implementation has to derive from the base WebSocketService class:

[ServiceBehavior(
    InstanceContextMode=InstanceContextMode.PerSession, 
    ConcurrencyMode=ConcurrencyMode.Multiple)]
internal sealed class NotificationService : WebSocketsService
{
    // ...
}

The service host is a type deriving from the ServiceHost named WebSocketsHost:

Uri baseAddress = new Uri("<uriString goes here>");            
WebSocketsHost<NotificationService> host =
    new WebSocketsHost<NotificationService>(baseAddress);
host.AddWebSocketsEndpoint();
host.Open();

Notice, that since your specify ConcurrencyMode.Multipe you have to manually handle synchronization and state using a synchronization construct. That means if the clients need only write-access to the data you can use a mutual exclusive lock (like the Monitor Class) otherwise you can use a lock like the ReaderWriterLockSlim Class (or a faster one).

Here is a summary of links about the WebSocket prototype for .NET: