WebSockets have revolutionized the way we communicate on the web. They provide a real-time, bidirectional communication channel between the client and server, enabling developers to create highly responsive and interactive web applications. If you’re a .NET Core developer, you’re in luck because .NET Core has built-in support for WebSockets. In this article, we’ll explore the power of WebSockets in .NET Core and show you how to use them to build real-time applications.
What are WebSockets?
WebSockets are a protocol that enables real-time, bidirectional communication between the client and server over a single TCP connection. Unlike HTTP, which is a request/response protocol, WebSockets allow the server to push data to the client at any time, without the client having to request it.
WebSockets were standardized in 2011 by the WebSocket API Working Group of the IETF, and are supported by all modern web browsers and many web servers.
Why use WebSockets?
There are several reasons why you might want to use WebSockets in your web applications:
- Real-time communication: With WebSockets, you can create real-time, bidirectional communication channels between the client and server. This enables you to build highly responsive and interactive web applications, such as chat applications, real-time collaboration tools, and games.
- Reduced latency: Because WebSockets allow the server to push data to the client at any time, you can reduce the latency of your application. This means that your application can respond faster to user actions, providing a better user experience.
- Reduced bandwidth: Because WebSockets use a single TCP connection, they can reduce the amount of bandwidth used by your application. This can be especially useful for mobile applications, where bandwidth is often limited.
WebSocket in .NET Core
.NET Core has built-in support for WebSockets, making it easy to create real-time web applications. The WebSocket support in .NET Core is provided by the Microsoft.AspNetCore.WebSockets package, which is included in the Microsoft.AspNetCore.App metapackage.
Creating a WebSocket endpoint
To create a WebSocket endpoint in .NET Core, you need to create a class that inherits from the Microsoft.AspNetCore.Http.WebSocketMiddleware class. This class provides the necessary infrastructure for handling WebSocket connections.
Here’s an example of a WebSocket endpoint that echos back any message it receives:
- Create a new .NET Core web application:
- Add the Microsoft.AspNetCore.WebSockets package:
- Create a new class called WebSocketHandler that inherits from WebSocketMiddleware:
- Modify the Startup class to use the WebSocketHandler:
- Run the application:
dotnet new web -o WebSocketDemo
dotnet add package Microsoft.AspNetCore.WebSockets
using System;using System.Net.WebSockets;using System.Threading;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Http.Extensions;using Microsoft.AspNetCore.WebSockets;namespace WebSocketDemo{public class WebSocketHandler : WebSocketMiddleware{public WebSocketHandler(RequestDelegate next) : base(next){}
public override async Task InvokeAsync(HttpContext context){if (context.WebSockets.IsWebSocketRequest){WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();await Echo(webSocket);}else{context.Response.StatusCode = 400;}}
private async Task Echo(WebSocket webSocket){byte[] buffer = new byte[1024 * 4];WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue){await webSocket.SendAsync(new ArraySegment(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None);}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);}}}
using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;namespace WebSocketDemo{public class Startup{public void ConfigureServices(IServiceCollection services){services.AddControllersWithViews();}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}
app.UseWebSockets();app.UseMiddleware();
app.UseRouting();
app.UseEndpoints(endpoints =>{endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");});}}}
dotnet run
You can now connect to the WebSocket endpoint using JavaScript or any other WebSocket client. Here’s an example of how to connect using JavaScript:
const socket = new WebSocket('ws://localhost:5000');socket.onopen = function(event) {console.log('WebSocket connected!');};
socket.onmessage = function(event) {console.log('Received message:', event.data);};
socket.onclose = function(event) {console.log('WebSocket disconnected!');};
socket.send('Hello, world!');
When you run this code, you should see the message ‘WebSocket connected!’ in the console. When you send a message using the send
method, the WebSocket endpoint will echo back the same message.
Handling WebSocket events
The WebSocketHandler class provides several virtual methods that you can override to handle WebSocket events:
OnConnectedAsync
: Called when a WebSocket connection is established.OnDisconnectedAsync
: Called when a WebSocket connection is closed.OnMessageAsync
: Called when a message is received from the client.OnErrorAsync
: Called when an error occurs.
Here’s an example of how to override the OnConnectedAsync
method to log a message when a new WebSocket connection is established:
public class WebSocketHandler : WebSocketMiddleware{public override async Task OnConnectedAsync(WebSocket socket){Console.WriteLine("WebSocket connected!");}}
Scaling WebSocket applications
Scaling WebSocket applications can be challenging because WebSockets establish a long-lived, persistent connection between the client and server. This means that a single WebSocket connection can tie up a server thread for a long period of time, potentially blocking other requests.
There are several strategies you can use to scale WebSocket applications:
- Load balancing: Use a load balancer to distribute WebSocket connections across multiple server instances. This can help to distribute the load and prevent any single server instance from becoming overwhelmed.
- Connection pooling: Use a connection pool to reuse WebSocket connections between requests. This can help to reduce the overhead of establishing new WebSocket connections.
- Asynchronous I/O: Use asynchronous I/O to handle WebSocket connections. This can help to free up server threads and improve scalability.
FAQ
What is .NET Core?
.NET Core is a free and open-source, cross-platform framework for building modern applications. It was developed by Microsoft and is designed to be fast, modular, and lightweight.
What is a WebSocket endpoint?
A WebSocket endpoint is a URL that is used to establish a WebSocket connection between the client and server. It typically begins with the ws://
or wss://
protocol scheme.
What is the Microsoft.AspNetCore.WebSockets package?
The Microsoft.AspNetCore.WebSockets package is a NuGet package that provides WebSocket support for .NET Core applications. It includes classes for handling WebSocket connections and messages.
What is the difference between HTTP and WebSockets?
HTTP is a request/response protocol that is used to transfer data between the client and server. WebSockets, on the other hand, provide a real-time, bidirectional communication channel between the client and server, enabling developers to create highly responsive and interactive web applications.
What are some use cases for WebSockets?
WebSockets can be used for a variety of real-time applications, including chat applications, real-time collaboration tools, games, and financial trading platforms.
Is WebSocket supported by all web browsers?
Yes, WebSockets are supported by all modern web browsers, including Chrome, Firefox, Safari, and Edge.
Is WebSocket secure?
WebSockets can be secured using the wss://
protocol scheme, which provides a secure, encrypted connection between the client and server. However, it’s important to note that securing WebSockets requires additional configuration and setup.