javascript - 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
解决方案
此页面的代码有效(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));
}
}
}
推荐阅读
- hibernate - 休眠排序规则配置
- sql-server - 加入内部视图非常慢
- c# - WPF - 将矢量图像绑定到增强的工具提示
- python-3.x - 如何检索在 AWS Lambda 函数上定义的环境变量
- spring-boot - 第一次调用 ZuulException (SendErrorFilter)
- java - 如何实现构造函数/析构函数对称,对于 Java
- php - 选择 * 不显示来自 Mysql 的记录
- rabbitmq - RabbitMq 中的磁盘节点与 Ram 节点
- codeigniter - Codeigniter 中的多次插入
- javascript - 图片未出现在 Firefox 上