Server-Sent Events (SSE) in ASP.NET Core for Real-Time Push Notifications

asp_dot_net_core

Server-Sent Events (SSE) in ASP.NET Core for Real-Time Push Notifications

Table of Contents

1. Introduction to Server-Sent Events

Server-Sent Events (SSE) is a technology that enables servers to send real-time updates to clients through a single HTTP connection. Unlike traditional methods where clients request updates, SSE allows for automatic and continuous updates, making it perfect for applications like news feeds, stock tickers, and more.

2. How SSE Works in ASP.NET Core

SSE in ASP.NET Core involves setting up a server endpoint that streams updates to clients in real-time. The client uses the EventSource API to receive these updates and react accordingly, all over a persistent HTTP connection.

3. Why Choose SSE Over WebSockets?

Both SSE and WebSockets allow real-time communication between the server and client, but SSE is ideal when you need one-way communication from the server to the client. SSE is simpler, uses standard HTTP, and has built-in reconnection and recovery mechanisms. It’s perfect for cases where the server needs to push updates without expecting client input.

4. SSE Event Stream Format

The data format for SSE is straightforward and involves sending the following fields:

  • data: The actual content of the message.
  • event: The event type (optional).
  • id: The event ID to keep track of messages (optional).
  • retry: Time in milliseconds to wait before retrying if the connection fails (optional).

5. Implementing SSE in ASP.NET Core

Here’s a basic example of implementing SSE in ASP.NET Core. We create a controller that sends data to the client:

Server-Side Implementation


[Route("api/notifications")]
public class NotificationController : ControllerBase
{
    [HttpGet]
    public async Task Get(CancellationToken cancellationToken)
    {
        HttpContext.Response.Headers.Add("Content-Type", "text/event-stream");

        while (!cancellationToken.IsCancellationRequested)
        {
            var message = $"data: Server time: {DateTime.Now}\n\n";
            await HttpContext.Response.WriteAsync(message);
            await HttpContext.Response.Body.FlushAsync();
            await Task.Delay(5000); // Wait for 5 seconds before sending the next update
        }
    }
}
    

Client-Side Implementation

On the client-side, use the EventSource API to receive updates:


const eventSource = new EventSource("/api/notifications");

eventSource.onmessage = function(event) {
    console.log("Message from server: ", event.data);
};
    

6. Example: Real-Time Notification System

Let’s say you want to implement a real-time notification system. The server sends updates to all connected clients when something changes:

Server-Side Example


public class NotificationService
{
    private static ConcurrentDictionary<string, StreamWriter> _clients = new();

    public static void AddClient(string id, StreamWriter writer)
    {
        _clients.TryAdd(id, writer);
    }

    public static void RemoveClient(string id)
    {
        _clients.TryRemove(id, out _);
    }

    public static async Task SendNotification(string message)
    {
        foreach (var client in _clients.Values)
        {
            await client.WriteAsync($"data: {message}\n\n");
            await client.FlushAsync();
        }
    }
}
    

This service keeps track of connected clients and sends notifications to all of them whenever new data arrives.

7. SSE Best Practices and Limitations

Best Practices

  • Send keep-alive comments to avoid connection timeouts.
  • Use HTTP/2 for efficient handling of multiple connections.
  • Secure the connection using HTTPS.

Limitations

  • SSE is one-way (server-to-client), unlike WebSockets which support two-way communication.
  • Some older browsers may not fully support SSE.
  • Be mindful of connection limits when multiple tabs are open.

8. Conclusion

Server-Sent Events (SSE) in ASP.NET Core provides a simple and efficient way to implement real-time push notifications from server to client. It’s perfect for scenarios where the server needs to send continuous updates without requiring client-side interaction. By leveraging SSE, you can build real-time web applications that deliver live data with minimal overhead and complexity.