【发布时间】:2022-11-10 23:38:05
【问题描述】:
我正在尝试使用 protobuf-net.grpc (.NET Framework 4.8) 中的 gRPC 服务器流在服务器和多个客户端之间编写通知系统。
我的服务基于this example。但是,如果我正确理解了这个例子,它只能处理一个订阅者(因为_subscriber 是StockTickerService 类的成员变量)。
我的测试服务如下所示:
private readonly INotificationService _notificationService;
private readonly Channel<Notification> _channel;
public ClientNotificationService(INotificationService notificationService)
{
_notificationService = notificationService;
_notificationService.OnNotification += OnNotification;
_channel = Channel.CreateUnbounded<Notification>();
}
private async void OnNotification(object sender, Notification notification)
{
await _channel.Writer.WriteAsync(notification);
}
public IAsyncEnumerable<Notification> SubscribeAsync(CallContext context = default)
{
return _channel.AsAsyncEnumerable(context.CancellationToken);
}
INotificationService 只是有一个事件OnNotification,它在调用它的Notify 方法时被触发。
然后我意识到 System.Threading.Channels 实现了生产者/消费者模式,但我需要发布者/订阅者模式。尝试时,确实只有一个客户收到通知,而不是所有客户。
如果服务器知道客户端何时断开连接也会很好,这在返回_channel.AsAsyncEnumerable 时似乎是不可能的。
那么我该如何修改它以便
- 服务多个客户,当
OnNotification被调用时,所有客户都会收到通知 - 并在客户端断开连接时记录?
【问题讨论】:
标签: c# .net publish-subscribe protobuf-net protobuf-net.grpc