Learn Server-Sent Events in C# .NET

Introduction

In modern web applications, real-time communication is increasingly important. Whether it's for live notifications, real-time updates, or streaming data, having a mechanism to push updates from the server to the client is crucial. While WebSockets and long-polling are common solutions, Server-Sent Events (SSE) provide a simpler and more efficient approach for certain use cases. In this article, we'll explore how to implement Server-Sent Events in a C# .NET application.

What Are Server-Sent Events (SSE)?

Server-Sent Events (SSE) is a server push technology that enables servers to send updates to clients over a single, long-lived HTTP connection. Unlike WebSockets, which allow bi-directional communication, SSE is uni-directional, meaning the server can push updates to the client, but the client cannot send messages back over the same connection.

SSE is built on top of HTTP and uses the text/event-stream MIME type. It’s supported natively by most modern browsers, making it an excellent choice for applications that need real-time updates with minimal setup.

Benefits of SSE

  • Simplicity: SSE is straightforward to implement and doesn’t require complex protocols or additional libraries.
  • Automatic Reconnection: If the connection drops, the browser automatically attempts to reconnect, making SSE reliable for intermittent connectivity.
  • Efficient Use of Resources: Unlike polling, SSE maintains a single connection, reducing the overhead associated with constantly establishing new connections.

Implementing Server-Sent Events in C# .NET
 

Step 1. Create an ASP.NET Core Web API Project

To get started, create a new ASP.NET Core Web API project. You can use the .NET CLI or Visual Studio.

dotnet new webapi -n SseExample

Step 2. Set Up the Controller

Next, create a controller that will handle the SSE connection. In this example, we’ll set up a simple endpoint that streams events to the client.

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace SseExample.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SseController : ControllerBase
    {
        [HttpGet("stream")]
        public async Task StreamEvents()
        {
            Response.ContentType = "text/event-stream";

            for (int i = 0; i < 10; i++)
            {
                await Response.WriteAsync($"data: Event {i}\n\n");
                await Response.Body.FlushAsync();
                await Task.Delay(1000); // Simulate a delay for each event
            }
        }
    }
}

In this code.

  • The StreamEvents method sets the response content type to text/event-stream.
  • A loop is used to send events to the client every second.
  • FlushAsync ensures that each event is sent immediately without buffering.

Step 3. Run the Application

Run your application and navigate to the /api/sse/stream endpoint. You’ll see a continuous stream of events being sent to the client. This simple example demonstrates how SSE can be used to push updates to a client.

Client-Side Implementation

On the client side, you can use JavaScript to handle the incoming events. The EventSource API makes this straightforward.

const eventSource = new EventSource('https://localhost:5001/api/sse/stream');

eventSource.onmessage = function(event) {
    console.log('New event:', event. Data);
};

In this code.

  • EventSource is used to open a connection to the SSE endpoint.
  • The onmessage event handler processes each incoming event.

Use Cases for Server-Sent Events

SSE is well-suited for scenarios where the server needs to push updates to the client, but the client doesn’t need to send data back to the same channel. Some common use cases include.

  • Live Sports Scores: Streaming real-time scores and updates to clients.
  • Stock Market Tickers: Pushing livestock prices to users.
  • Notifications: Sending real-time notifications to users, such as chat messages or system alerts.

Considerations and Limitations

While SSE is a powerful tool, it’s essential to consider its limitations.

  • Uni-directional Communication: SSE only supports server-to-client communication. If bi-directional communication is required, WebSockets might be a better choice.
  • Browser Support: While most modern browsers support SSE, it's not universally available in older browsers.
  • Connection Limits: Some browsers limit the number of concurrent SSE connections per domain, which may affect scalability in certain scenarios.

Conclusion

Server-sent events provide a simple yet effective way to implement real-time updates in web applications. With minimal setup, you can push live data to your clients using a single, persistent HTTP connection. By understanding how to implement SSE in C# .NET, you can easily add real-time capabilities to your applications.

SSE offers a reliable and efficient solution, whether you're building a live dashboard, streaming notifications, or pushing updates. Start exploring SSE in your projects today and harness the power of real-time communication!


Similar Articles