简体   繁体   中英

gRPC C# server side, waiting until client closes connection?

I am creating a gRPC service that allows clients to public interface

My protofile:

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);
}

My C# server:

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;
    }
}

How do I know when the client disconnects?

When the client disconnects, context.CancellationToken will be canceled. Pass it to your awaitable method so that it can terminate.

I have a sample here. https://github.com/cactuaroid/GrpcWpfSample/blob/cd0d87ed6ccccac787960e9742aee036a3dc11eb/GrpcWpfSample.Server/Grpc/ChatServiceGrpcServer.cs#L51

ForEachAwaitAsync() will throw TaskCanceledException when the given CancellationToken is canceled, then it catches the exception and log the disconnection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM