joydip_kanjilal
Contributor

How to work with Web Sockets in .Net

opinion
Jun 24, 20164 mins
Software Development

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

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();

        }

   }

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author