首页 > 解决方案 > C# .NET 5.0 中的 Javascript“事件源”

问题描述

我的公司选择“Mercure”(https://mercure.rocks/docs/getting-started)来管理服务器发送的事件。我们在服务器上安装“Mercure HUB”,现在,在 C# .NET 5.0 中,我必须实现服务器端(发布者,我已经实现)和客户端(订阅者)。订阅者必须使用 WPF 完成

从“入门”页面我可以看到一个需要转换为 C# 的 Javascript 示例 我不知道如何在 C# 中管理“EventSource” 有什么想法吗?

// 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

标签: javascriptc#wpf.net-5eventsource

解决方案


此页面的代码有效(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));
        }
    }
}

推荐阅读