Using WebSockets with asp.net WebAPI

In the below post we will learn how to create an WebSockets enabled webAPI service and use it with a WebSocket client.

First of all, To use webSockets you must  use ASP.NET 4.5 so with MS Visual studio 2012 , you can proceed , but to test it , you will need windows 8 or windows server 2012 which supports web sockets.

image

Now install the “Microsoft.WebSockets” package from Nuget using package manager console to get the support of websockets development.

 image

This package provide facility to creating and handling websocket connection in webAPI environment. below are the example code for a api controller class which can handle websocket request and communicates with an websocket client.

   1:  using Microsoft.Web.WebSockets;
   2:  using System;
   3:  using System.Collections.Generic;
   4:  using System.Linq;
   5:  using System.Net;
   6:  using System.Net.Http;
   7:  using System.Web;
   8:  using System.Web.Http;
   9:   
  10:  namespace MYWebSocketChatApp.Controllers
  11:  {
  12:      public class ChatAppController : ApiController
  13:      {
  14:          public HttpResponseMessage Get()
  15:          {
  16:              HttpContext.Current.AcceptWebSocketRequest(new MyChatAppWebSocketHandler());
  17:              return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
  18:          }
  19:      }
  20:   
  21:      class MyChatAppWebSocketHandler : WebSocketHandler
  22:      {
  23:          public static WebSocketCollection _connectedChatClients;
  24:          private string _userId = string.Empty;
  25:   
  26:          static MyChatAppWebSocketHandler()
  27:          {
  28:              _connectedChatClients = new WebSocketCollection();
  29:          }
  30:   
  31:          public override void OnOpen()
  32:          {
  33:              base.OnOpen();
  34:              _userId = new Random().Next(1, 10000).ToString(); //Random userId
  35:              _connectedChatClients.Add(this);
  36:              this.Send(_userId);
  37:          }
  38:   
  39:          public override void OnClose()
  40:          {
  41:              _connectedChatClients.Remove(this);
  42:              base.OnClose();
  43:          }
  44:          public override void OnMessage(string message)
  45:          {
  46:              _connectedChatClients.Broadcast(_userId+ " : "+ message);
  47:              base.OnMessage(message);
  48:          }
  49:   
  50:      }
  51:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The “WebSocket” handler class in a class which can handle/communicate with a websocket client, so after inheriting this we can customize its functionality.

Below are the example code for a html page which can start websocket connection and listen different event of it.

   1:  <!DOCTYPE html>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:      <title>Random Chat</title>
   5:      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
   6:  
   7:  
   8:      <form id="randomChatForm">
   9:          <label id="yourRandomId">
  10:          <div id="chatMessages" />
  11:          <input id="yourInput" />
  12:          <input type="submit" id="sendButton" value="Submit" />
  13:      
  14:      
  15:   
  16:      <script type="text/javascript">
  17:          $(document).ready(function () {
  18:   
  19:              var websocketURI = new WebSocket("ws://localhost:52458//api/chatapp/");
  20:   
  21:              $("#sendButton").click(function (ev) {
  22:                  websocketURI.send($("#yourInput").val());
  23:              });
  24:   
  25:              websocketURI.onopen = function (ev) {
  26:                  $("#yourRandomId").text(ev.data);
  27:              }
  28:   
  29:              websocketURI.onclose = function (ev) {
  30:                  $("#yourRandomId").text("You are disconnected");
  31:              }
  32:   
  33:              websocketURI.onmessage = function (ev) {
  34:                  $("#chatMessages").append(ev.data);
  35:              }
  36:          });
  37:   
  38:      </script>
  39:  </body>
  40:  </html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

In the above code a JavaScript variable named “websocketURI” represents a websocket uri. here “ws” represents that its an websocket request. you can add event listener which trigger when a specific type of event occurs in websocket. here “onopen”,”onclose” etc are example of these events. please create a sample asp.net webAPI project using the above code and try it on IIS 8.0 + windows 8 environment on the .net framework 4.5 or above.

Hope you find this post useful, thanks for reading.

Advertisements

2 thoughts on “Using WebSockets with asp.net WebAPI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s