How to work with Web Sockets in .Net

WebSockets implement fast, secure, bi-directional, full duplex communication between a client and a server to support real-time, low-latency messaging

Websockets

Websockets

A web socket is a TCP socket connection between the client and the server over a network. Essentially, a web socket is a two-way full duplex communication between the client and the server over a network. The increasing demand for real time, low latency messaging for web, mobile applications alike has led to the advent of web sockets. This is a protocol that enables you to provide real time, fast, bi-directional communication in your applications sans the need of compromising on the user experience.

WebSockets is a message based protocol that takes advantage of a TCP streamed connection. The System.Net.WebSockets namespace provides support for working with web sockets in .Net. Note that a web socket connection between a server and a client application is established through a HTTP handshake exchange between them.

The MSDN states: "WebSockets enable browsers to open a bidirectional, full-duplex communication channel with services. Each side can then use this channel to immediately send data to the other. Now, sites from social networking and games to financial sites can deliver better real-time scenarios, ideally using same markup across different browsers."

You can learn more about the WebSocket protocol here.

Working with WebSockets in .Net

When hosting your web sockets at the server side using .Net, you have a few choices. You can host a WebSocket server in traditional ASP.Net or ASP.Net MVC applications. To do this, you would need to take advantage of HttpContext.AcceptWebSocketRequest. You can then have a web application at the client side to connect to the web socket and communicate for exchange of messages. You can also create a WCF service that uses netHttpBinding and take advantage of a CallbackContract in your service. You can then take advantage of HttpContext.AcceptWebSocketRequest or even leverage WebSocketHandler or WebSocketHost available as part of Microsoft.WebSockets.dll.

At the client side, you can take advantage of HTML5 and jQuery in your web page. You can also leverage ClientWebSocket class to create a client application or even use a WCF client to connect to the web socket.

Note that the HttpContext object now (since .Net Framework 4.5) contains a new property called IsWebSocketRequest. You can take advantage of this property of the HttpContext object to check if an incoming request is a web socket request. The following code listing shows how you can create a web socket using HttpHandler.

public class IDGService : IHttpHandler

   {

       public void ProcessRequest(HttpContext context)

       {

           if (context.IsWebSocketRequest)

               context.AcceptWebSocketRequest(ProcessRequestInternal);

           else

               context.Response.StatusCode = 400;

       }

       public bool IsReusable

       {

           get

            {

               return false;

           }

       }

       private async Task ProcessRequestInternal(AspNetWebSocketContext context)

       {

           WebSocket socket = context.WebSocket;

             while(true)

           {

               //Write your code here to process the request

           }

       }

   }

You should register the Http handler in your application's web.config file. Here's the code snippet that demonstrates how you should do this.

<system.webServer>

   <handlers>

     <add path="/IDGWeb/IDGHandler.ashx" verb="*" name="IDGHandler"

           type="IDGWeb.IDGHandler"/>

   </handlers>

</system.webServer>

You can also use web sockets in your Web API controllers. Incidentally, ASP.Net Web API is a lightweight framework used for building RESTful services that run on HTTP. RESTful services are light-weight, stateless, client-server based, cacheable services that are based on the concept of resources. The following code snippet illustrates how you can implement a web socket in your Web API controller method -- note the usage of HttpContext.AcceptWebSocketRequest to accept and establish connections.

public class IDGWebSocketController : ApiController

{

       [HttpGet]

       public HttpResponseMessage GetMessage()

       {

           if (HttpContext.Current.IsWebSocketRequest)

           {

               HttpContext.Current.AcceptWebSocketRequest(ProcessRequestInternal);

           }

           return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);

       }

          private async Task ProcessRequestInternal(AspNetWebSocketContext context)

          {

          //Write your code here to process the request

         }

}

At the client side, you would need to connect to the web socket by specifying the URI used to send the WebSocket connection request.

var webSocket = new WebSocket("ws://" + window.location.hostname +

                   "/IDGWeb/api/IDGWebSocket");

                   webSocket.onopen = function () {

                   $("#status").text("Connected...");

               };

You can also take advantage of the new Microsoft.Web.WebSockets.WebSocketHandler class to implement web sockets now. To use this class, you would need to install the Microsoft.WebSockets package via NuGet Package Manager. Alternatively, you can install the same package by running the following command in the NuGet Package Manager Console.

Install-Package Microsoft.WebSockets

The following code snippet shows how you can extend the WebSocketHandler class to create your own custom handler.

public class IDGWebSocketHandler : WebSocketHandler

   {

       private static WebSocketCollection socketClients = new WebSocketCollection();

       public override void OnOpen()

       {

           socketClients.Add(this);

           socketClients.Broadcast("This is for all connected clients...");

           this.Send("Hello from: " + this.WebSocketContext.UserHostAddress);

       }

       public override void OnClose()

       {

           base.OnClose();

       }

       public override void OnError()

       {

           base.OnError();

        }

   }

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.