Real-Time Data Transfer with WebSockets and SignalR in .NET Core

Introduction

In today's dynamic web applications, real-time data transfer has become a crucial aspect of providing a responsive and interactive user experience. WebSocket technology, along with frameworks like SignalR in .NET Core, enables bidirectional communication between clients and servers, allowing seamless data exchange.

In this article, we'll explore how to implement WebSocket functionality using SignalR in a .NET Core application to retrieve data from a concurrent dictionary and push it to clients in real time.

Understanding WebSockets and SignalR

WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection, allowing for low-latency, bidirectional communication between clients and servers. It enables real-time data transfer without the overhead of HTTP polling.

SignalR is a high-level library built on top of WebSocket that simplifies real-time web functionality implementation in .NET applications. It abstracts away the complexities of managing connections and allows developers to focus on building real-time features.

Setting Up the Project

First, ensure you have the .NET Core SDK installed on your system. You can create a new .NET Core Web API project using the following command:

dotnet new webapi -n WebSocketSignalRDemo

Next, navigate to the project directory:

cd WebSocketSignalRDemo

Install the required SignalR package:

dotnet add package Microsoft.AspNetCore.SignalR

Implementing WebSocket Functionality

  1. Create a Concurrent Dictionary: In this example, let's assume we have a concurrent dictionary where real-time data updates occur. For demonstration purposes, we'll simulate this with a simple dictionary containing stock prices.
  2. Set Up SignalR Hub: Create a SignalR hub that will handle client connections and data transmission. Add methods to retrieve data from the concurrent dictionary and send it to clients.
  3. Configure SignalR in Startup: Register SignalR services and endpoints in the Startup.cs file.
  4. Client-Side Integration: Implement WebSocket client logic to receive real-time updates from the server.

Example Code

Here's a simplified implementation of the above steps:

// Concurrent Dictionary Simulation (Replace with actual data source)
ConcurrentDictionary<string, decimal> stockPrices = new ConcurrentDictionary<string, decimal>();

// SignalR Hub
public class StockTickerHub : Hub
{
    public async Task GetLatestStockPrices()
    {
        while (true)
        {
            // Simulated data update
            foreach (var kvp in stockPrices)
            {
                await Clients.All.SendAsync("UpdateStockPrice", kvp.Key, kvp.Value);
            }
            await Task.Delay(1000); // Simulated delay
        }
    }
}

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapHub<StockTickerHub>("/stockTickerHub");
    });
}

// Client-Side (JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Ticker</title>
</head>
<body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.7/signalr.min.js"></script>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/stockTickerHub")
            .build();

        connection.on("UpdateStockPrice", (symbol, price) => {
            const stockList = document.getElementById("stockList");
            const listItem = document.createElement("li");
            listItem.textContent = `${symbol}: $${price}`;
            stockList.appendChild(listItem);
        });

        connection.start()
            .then(() => connection.invoke("GetLatestStockPrices"))
            .catch(err => console.error(err));
    </script>
</body>
</html>

Conclusion

Implementing real-time data transfer with WebSockets and SignalR in .NET Core offers a powerful way to create interactive and responsive web applications. By leveraging WebSocket technology and SignalR's abstractions, developers can build features like live updates, chat applications, and more, enhancing user engagement and experience.

😊Please consider liking and following me for more articles and if you find this content helpful.👍


Citiustech Healthcare Technology Pvt Ltd
CitiusTech plays a deep and meaningful role in powering the future of healthcare.