DEV Community

Aayush
Aayush

Posted on

5

Using server sent events in ASP.NET

I am assuming you already have your ASP.NET project ready, I will just straight into implementing SSEs for sending realtime updates to client.

1. Create a Controller for sending SSEs.

public class EventsController : ControllerBase
    {
        private static readonly List<StreamWriter> _clients = [];

        [HttpGet]
        public async Task Subscribe()
        {
            Response.Headers.Append("Content-Type", "text/event-stream");
            Response.Headers.Append("Cache-Control", "no-cache");
            Response.Headers.Append("Connection", "keep-alive");

            var streamWriter = new StreamWriter(Response.Body);
            _clients.Add(streamWriter);

            try
            {
                while (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromSeconds(1), HttpContext.RequestAborted);
                }
            }
            finally
            {
                _clients.Remove(streamWriter);
            }
        }

        public static async Task NotifyClients(string data)
        {
            List<StreamWriter> deadClients = [];

            foreach (var client in _clients)
            {
                try
                {
                    await client.WriteAsync($"data: {data}\n\n");
                    await client.FlushAsync();
                }
                catch
                {
                    deadClients.Add(client);
                }
            }

            foreach (var deadClient in deadClients)
            {
                _clients.Remove(deadClient);
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

2. Use the NotifyClients method to send SSEs
Where ever in your code you want to send an event just call the NotifyClients methods with any data. It will be sent to all subscribed clients.

[HttpPost]
public async Task<IActionResult> CreatePost(CreatePostDto createPostDto)
{
    // save new post to database

    // send SSE to all the clients
    await EventsController.NotifyClients("post created");

    return Ok("Post created successfully");
}
Enter fullscreen mode Exit fullscreen mode

3. Usage in client-side

const connectToSSE = () => {
    const eventSource = new EventSource('/api/events');

    eventSource.onmessage = (event) => {
        console.log('New data received:', event.data);
        // Do something
    };

    eventSource.onerror = (error) => {
        console.error('SSE error:', error);
        eventSource.close();
    };
};
Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay