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(); } } Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos