Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A Sneak Preview of WebSocket-enabled WCF Services

0.00/5 (No votes)
5 Jun 2012CPOL1 min read 6.9K  
A WebSocket-enabled service in .NET will be written like any other WCF service with two differences.

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:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)