如何处理服务器上客户端的断开连接

时间:2020-06-30 09:37:33

标签: go grpc

我正在使用gRPC构建监视系统。为此,我需要知道gRPC客户端是否崩溃并因此与gRPC服务器断开连接。

这就是我创建服务器的方式。

var kaep = keepalive.EnforcementPolicy{
    MinTime:             5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection
    PermitWithoutStream: true,            // Allow pings even when there are no active streams
}

var kasp = keepalive.ServerParameters{
    MaxConnectionIdle:     15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY
    MaxConnectionAgeGrace: 5 * time.Second,  // Allow 5 seconds for pending RPCs to complete before forcibly closing connections
    Time:                  5 * time.Second,  // Ping the client if it is idle for 5 seconds to ensure the connection is still active
    Timeout:               1 * time.Second,  // Wait 1 second for the ping ack before assuming the connection is dead
}

    s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp))
    pb.RegisterHeartbeatGRPCServer(s, bt)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }

我发现,保持活动的概念可能对检测断开连接的客户端很有用。 https://github.com/grpc/grpc-go/blob/master/Documentation/keepalive.md

但是,我不确定如何处理断开连接。

如何处理这种断开?更确切地说,我想在客户端断开连接时调用函数ClientDisconnected(clientId)。有可能吗?

1 个答案:

答案 0 :(得分:0)

您可能想为此使用统计处理程序。特别是,您正在寻找ConnEnd操作:

https://godoc.org/google.golang.org/grpc/stats#ConnEnd https://godoc.org/google.golang.org/grpc/stats#Handler(您正在寻找TagConn和HandleConn) https://godoc.org/google.golang.org/grpc#StatsHandler