登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-02 16:54:35 335浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《如何处理服务器上客户端断开连接的情况》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在使用 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) 。这可能吗?


解决方案


您可能想为此使用统计处理程序。特别是,您正在寻找 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

理论要掌握,实操不能落!以上关于《如何处理服务器上客户端断开连接的情况》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>