In the previous article of this series, we discussed the URL rewriting middleware concept within .NET Core applications. Now in this article, we will discuss about web sockets and how to use web sockets in ASP.NET Core applications.
If you want to look at the previous articles, please visit the links given below.
So, before starting the detailed work, first we need to understand what is Web Socket and how it performs its operations.
Actually, Web Socket is one type of communication protocol which provides full duplex communication channel over a TCP connection. Web Socket is mainly designed for implementing within web servers and web browsers. However, we can implement Web Socket at any client or server application since it is totally independent of TCP based protocols. It is used for applications such as chat, stock tickers, games, anywhere you want real-time functionality in a web application.
How Web Socket works
Web Socket actually provides a persistent or steady connection between a server and a client so that both the sides can send data to the other side any time. The client establishes a WebSocket connection through a process known as the WebSocket Handshake. This process starts with the client sending a regular HTTP request to the server.
A brief history of Real-Time Web Applications
In the early ages of web development, web sites were basically developed to mainly fulfill only idea i.e. client can send request of fetching any type of data to the Server and on the other hand, Sever must fulfill the request to send back those data to the client. But in the year of 2005, with the introduction of AJAX, this basic concept of web application changed.
At that time, people wanted to develop bidirectional web applications or sites for establishing connection between Client and Server with the help of AJAX. Web applications have grown up a lot and are now consuming more data than ever before. The biggest thing holding them back was the traditional HTTP model of client initiated transactions. To overcome this, a number of different strategies were devised to allow Servers to
push data to the Client. One of the most popular of these strategies was
long-polling.
This involves keeping an HTTP connection open until the Server has some data to push down to the client. But there was a problem in case of HTTP connection. Actually, against each and every HTML request, a bunch of headers and cookies data are transferred from the client machine to the Server, which kills the network bandwidth. But if we want to develop a web based application like game or chat application where data transmission volume in one of the key elements, the worst part of this is that a lot of these headers and cookies aren’t actually needed to fulfill the client’s request.
What we really need is a way of creating a persistent, low latency connection that can support transactions initiated by either the client or server. This is exactly what Web Sockets provide and in this post you are going to learn all about how to use them in your own applications.
When to use it
Web Socket is an advanced technology that makes it possible to establish an interactive connection between server and client browser’s. With this technology or API, we can send message to a server from client and also can receive an event driven response without having any TCP or HTTP protocol use. ASP.NET SignalR provides a richer application model for real-time functionality, but it runs only on ASP.NET, not ASP.NET Core. A Core version of SignalR is under development. But you might have to develop features that SignalR would provide, such as:
- Support for a broader range of browser versions by using automatic fallback to alternative transport methods.
- Automatic reconnection when a connection drops.
- Support for clients calling methods on the server or vice versa.
- Support for scaling to multiple servers.
How to use it
- Install the Microsoft.AspNetCore.WebSockets package from Nuget Package Manager.
- Configure the middleware.
- Accept WebSocket requests.
- Send and receive messages
Configure the middleware
Add the WebSockets middleware in the Configure method of the Startup.cs class.
The following settings can be configured,
KeepAliveInterval
How frequently to send "ping" frames to the client, to ensure proxies keep the connection open.
ReceiveBufferSize
The size of the buffer used to receive data. Only advanced users would need to change this, for performance tuning based on the size of their data.
- var wsOptions = new WebSocketOptions()
- {
- KeepAliveInterval = TimeSpan.FromSeconds(120),
- ReceiveBufferSize = 4 * 1024
- };
- app.UseWebSockets(wsOptions);
Accept WebSocket requests
Somewhere later in the request life cycle check if it's a Web Socket request and accept the Web Socket request. This example is from later in the Configure method,
- app.Use(async (context, next) =>
- {
- if (context.Request.Path == "/ws")
- {
- if (context.WebSockets.IsWebSocketRequest)
- {
- WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
- await Echo(context, webSocket);
- }
- else
- {
- context.Response.StatusCode = 400;
- }
- }
- else
- {
- await next();
- }
- });
Send and receive messages
When we want to transfer message from server to client or vice versa, then we need to call AcceptWebSocketAsync method to upgrades the TCP connection to a WebSocket connection and it gives us a WebSocket object. Use the WebSocket object to send and receive messages. The code receives a message and immediately sends back the same message. It stays in a loop doing that until the client closes the connection.
- private async Task Echo(HttpContext context, WebSocket webSocket)
- {
- var buffer = new byte[1024 * 4];
- WebSocketReceiveResult wsresult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
- CancellationToken.None);
- while (!result.CloseStatus.HasValue)
- {
- await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), wsresult.MessageType,
- wsresult.EndOfMessage, CancellationToken.None);
- wsresult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
- }
- await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription,
- CancellationToken.None);
- }
When you accept the Web Socket before beginning this loop, the middleware pipeline ends. Upon closing the socket, the pipeline unwinds, that is, the request stops moving forward in the pipeline when you accept a Web Socket, just as it would when you hit an MVC action. But when you finish this loop and close the socket, the request proceeds back up the pipeline.
Program.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Hosting;
-
- namespace Prog8_WebSocket
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- var host = new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseIISIntegration()
- .UseStartup<Startup>()
- .Build();
-
- host.Run();
- }
- }
- }
Startup.cs
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Net.WebSockets;
- using System.Threading;
- using System.Threading.Tasks;
-
- namespace Prog8_WebSocket
- {
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- }
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- loggerFactory.AddConsole(LogLevel.Debug);
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseWebSockets();
-
- var webSocketOptions = new WebSocketOptions()
- {
- KeepAliveInterval = TimeSpan.FromSeconds(120),
- ReceiveBufferSize = 4 * 1024
- };
- app.UseWebSockets(webSocketOptions);
-
- app.Use(async (context, next) =>
- {
- if (context.Request.Path == "/ws")
- {
- if (context.WebSockets.IsWebSocketRequest)
- {
- WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
- await Echo(context, webSocket);
- }
- else
- {
- context.Response.StatusCode = 400;
- }
- }
- else
- {
- await next();
- }
- });
- app.UseFileServer();
- }
-
- private async Task Echo(HttpContext context, WebSocket webSocket)
- {
- var buffer = new byte[1024 * 4];
- WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
- while (!result.CloseStatus.HasValue)
- {
- await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
- result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
- }
- await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
- }
-
- }
- }
Index.html
Now, run the code from command prompt. The output is shown below.
You can read the next part here,