Introduction
Creating a complete example of real-time communication using the WebSocket protocol in ASP.NET Core involves several steps. In this example, we will create a simple chat application where users can send and receive messages in real-time. This example assumes you have a basic understanding of ASP.NET Core and C#.
Step 1. Create a new ASP.NET Core project
First, create a new ASP.NET Core project using Visual Studio or the command line. You can choose the ASP.NET Core Web Application template and select the Empty template.
Step 2. Install WebSocket NuGet Package
In your project, you need to install Microsoft.AspNetCore.WebSockets NuGet package, which provides WebSocket support.
dotnet add package Microsoft.AspNetCore.WebSockets
Step 3. Create a WebSocket Middleware
In your Startup.cs file, configure WebSocket middleware in the Configure method.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebSocketChatApp.Middleware;
Author: Sardar Mudassar Ali Khan
namespace WebSocketChatApp
{
public class Startup
{
// ... other configurations ...
public void ConfigureServices(IServiceCollection services)
{
// ... other services ...
services.AddWebSocketManager();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... other middleware ...
app.UseWebSockets();
app.MapWebSocketManager("/chat", app.ApplicationServices.GetService<ChatWebSocketHandler>());
// ... other configurations ...
}
}
}
Step 4. Create a WebSocket Handler
Create a WebSocket handler class to manage WebSocket connections and messages. You can name it ChatWebSocketHandler.cs.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
Author: Sardar Mudassar Ali Khan
namespace WebSocketChatApp.Middleware
{
public class ChatWebSocketHandler
{
private readonly WebSocketConnectionManager _connectionManager;
private readonly ILogger<ChatWebSocketHandler> _logger;
public ChatWebSocketHandler(WebSocketConnectionManager connectionManager, ILogger<ChatWebSocketHandler> logger)
{
_connectionManager = connectionManager;
_logger = logger;
}
public async Task HandleWebSocket(HttpContext context, WebSocket webSocket)
{
var socketId = _connectionManager.AddSocket(webSocket);
_logger.LogInformation($"WebSocket connection established with ID {socketId}");
while (webSocket.State == WebSocketState.Open)
{
var message = await ReceiveMessageAsync(webSocket);
if (message != null)
{
_logger.LogInformation($"Received message from ID {socketId}: {message}");
await BroadcastMessageAsync(message);
}
}
_connectionManager.RemoveSocket(socketId);
_logger.LogInformation($"WebSocket connection closed with ID {socketId}");
}
private async Task<string?> ReceiveMessageAsync(WebSocket webSocket)
{
var buffer = new byte[1024];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.CloseStatus.HasValue)
{
return null;
}
return System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
}
private async Task BroadcastMessageAsync(string message)
{
foreach (var socket in _connectionManager.GetAllSockets())
{
if (socket.Value.State == WebSocketState.Open)
{
await socket.Value.SendAsync(System.Text.Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
}
Sandra MartosPosted Jun 11, 2024, 8:54 AM
Hello, can I get a link to the project please? Thank you
RushitaPosted May 23, 2024, 7:43 AM
Can you share git project link?
Balamurugan ThanikachalamPosted Nov 21, 2023, 3:17 AM
Implementation of extension methods 1)services.AddWebSocketManager(); and 2)app.MapWebSocketManager("/chat", app.ApplicationServices.GetService<ChatWebSocketHandler>()); are not found.