Javascript "EventSource" in C# .NET 5.0

1k views Asked by At

my company choose "Mercure" (https://mercure.rocks/docs/getting-started) to manage Server-Sent Events. We install "Mercure HUB" on a server and now, in C# .NET 5.0, I must implement the server-side (publisher, that I already implemented) and the client-side (subscriber). The subscriber must be done with a WPF

From the "getting-started" page I can see a Javascript example that I need to transform into C# I don't know how to manage a "EventSource" in C# Any ideas ?

// The subscriber subscribes to updates for the https://example.com/users/dunglas topic
// and to any topic matching https://example.com/books/{id}
const url = new URL('https://localhost/.well-known/mercure');
url.searchParams.append('topic', 'https://example.com/books/{id}');
url.searchParams.append('topic', 'https://example.com/users/dunglas');
// The URL class is a convenient way to generate URLs such as https://localhost/.well-known/mercure?topic=https://example.com/books/{id}&topic=https://example.com/users/dunglas
const eventSource = new EventSource(url);
// The callback will be called every time an update is published
eventSource.onmessage = e => console.log(e); // do something with the payload
1

There are 1 answers

0
Vez On

The code of this page works (https://makolyte.com/event-driven-dotnet-how-to-consume-an-sse-endpoint-with-httpclient/)

static async Task Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(5);
    string stockSymbol = "VTSAX";
    string url = $"http://localhost:9000/stockpriceupdates/{stockSymbol}";

    while (true)
    {
        try
        {
            Console.WriteLine("Establishing connection");
            using (var streamReader = new StreamReader(await client.GetStreamAsync(url)))
            {
                while (!streamReader.EndOfStream)
                {
                    var message = await streamReader.ReadLineAsync();
                    Console.WriteLine($"Received price update: {message}");
                }
            }
        }
        catch(Exception ex)
        {
            //Here you can check for 
            //specific types of errors before continuing
            //Since this is a simple example, i'm always going to retry
            Console.WriteLine($"Error: {ex.Message}");
            Console.WriteLine("Retrying in 5 seconds");
            await Task.Delay(TimeSpan.FromSeconds(5));
        }
    }
}