dongyue9864 2016-10-03 06:30
浏览 2182

grpc go:当客户端关闭连接时,如何在服务器端知道

I am using grpc go

i have an rpc which looks roughly like this

196 service MyService {
197   // Operation 1
198   rpc Operation1(OperationRequest) returns (OperationResponse) {
199       option (google.api.http) = {
200         post: "/apiver/myser/oper1"
201         body: "*"
202     };
203   }

Client connects by using grpc.Dial() method

When a client connects, the server does some book keeping. when the client disconnects, the bookkeeping needs to be removed.

is there any callback that can be registered which can be used to know that client has closed the session.

  • 写回答

1条回答 默认 最新

  • drus40229 2018-07-18 09:07
    关注

    Assuming that the server is implemented in go, there's an API on the *grpc.ClientConn that reports state changes in the connection.

    func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool
    

    https://godoc.org/google.golang.org/grpc#ClientConn.WaitForStateChange

    These are the docs on each of the connectivity.State

    https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md

    If you need to expose a channel that you can listen to for the client closing the connection then you could do something like this:

    func connectionOnState(ctx context.Context, conn *grpc.ClientConn, states ...connectivity.State) <-chan struct{} {
        done := make(chan struct{})
    
        go func() {
            // any return from this func will close the channel
            defer close(done)
    
            // continue checking for state change 
            // until one of break states is found
            for { 
                change := conn.WaitForStateChange(ctx, conn.GetState())
                if !change {
                    // ctx is done, return
                    // something upstream is cancelling
                    return
                }
    
                currentState := conn.GetState()
    
                for _, s := range states {
                    if currentState == s {
                        // matches one of the states passed
                        // return, closing the done channel
                        return 
                    }
                }
            }
        }()
    
        return done
    }
    

    If you only want to consider connections that are shutting down or shutdown, then you could call it like so:

    // any receives from shutdownCh will mean the state Shutdown
    shutdownCh := connectionOnState(ctx, conn, connectivity.Shutdown) 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据