2017-12-21 09:53
浏览 284


I am using go-grpc to create a bidirectional stream. When I unplug the cable, the server doesn't known client is dead for a very very long time. How can I detect client is gone in this case ???

图片转代码服务由CSDN问答提供 功能建议

我正在使用go-grpc创建双向流。 当我拔下电缆时,服务器不知道客户端已经关闭了很长时间。 在这种情况下,如何检测客户端不存在?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doufei9946 2017-12-21 14:51

    Your GRPC server-side handler will know about client context cancellation the next time it will try to Send/Recv message to/from stream: the error will be returned:

    func (s *server) handler(stream your_service.Stream) error {
        if err := stream.Recv(); err != nil {
            // you will have context cancelation error here

    In some cases it may be useful to check context cancellation explicitly:

    func (s *server) handler(stream your_service.Stream) error {
         // some logic
         select {
             case <-stream.Context().Done():
                 return stream.Context().Err()

    By the way, do you unplug the cable literally? Because it may be treated in different ways by the operational system. Why don't you use any modern virtualization tools, like Docker, for your tests?

    打赏 评论
  • dsq30861 2018-04-16 21:25

    I had the exact same problem as you did. In my case, when I used Ctrl-C to terminate my test client, the server detected it pretty quickly, but when I used Ctrl-Z (or if I cut power to my micro-controller) the server would take forever to close the hanging connection. You need to use some sort of heartbeat to check on the connection using something like gRPC's keepAlive feature. I had to create my own heartbeat message that I sent periodically because of a problem with using gRPC behind Envoy (https://github.com/envoyproxy/envoy/issues/2086)

    打赏 评论