我正在创建一个gRPC服务,该服务允许客户端公开接口
我的原型文件:
syntax = "proto3";
package Tests;
import "google/protobuf/any.proto";
message ListenTest1EventStream {
uint64 objectId = 1;
}
message EventTestEvent {
}
service Test1ObjectService {
rpc ListenEvents (ListenTest1EventStream) returns (stream google.protobuf.Any);
}
我的C#服务器:
ISomeService
{
event EventHandler<EventArgs> TestEvent;
}
public class Server : Test1ObjectService.Test1ObjectServiceBase
{
private readonly ISomeService _someService;
public Server(ISomeService someService)
{
_someService = someService;
}
public override async Task ListenEvents(ListenTest1EventStream request, IServerStreamWriter<Any> responseStream, ServerCallContext context)
{
// Begin monitoring event handlers, wait indefinitely
var handler = new EventHandler<EventArgs>((sender, args) =>
{
responseStream.WriteAsync(Any.Pack(new EventTestEvent()));
});
_someService.TestEvent += handler;
// TODO: Wait until response stream is forcibly closed. How?
await responseStream.WaitForSatusChangedOrSomething();
_someService.TestEvent -= handler;
}
}
我怎么知道客户端何时断开连接?
答案 0 :(得分:0)
当客户端断开连接时,context.CancellationToken
将被取消。将其传递给您等待的方法,以便它可以终止。
ForEachAwaitAsync()
将在给定的TaskCanceledException
被取消时抛出CancellationToken
,然后捕获异常并记录断开连接。