Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grpc go : how to know in server side, when client closes the connection

Tags:

go

grpc

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.

like image 662
weima Avatar asked Oct 03 '16 06:10

weima


1 Answers

Based on your code, it's an unary rpc call, the client connect to server for only one time, send a request and get a response. The client will wait for the response until timeout.

In server side streaming, you can get the client disconnect from

<-grpc.ServerStream.Context.Done()

signal.

With that above, you can implement your own channel in a go routine to build your logic. Use select statement as:

select {
    case <-srv.Context().Done():
        return
    case res := <-<YOUR OWN CHANNEL, WITH RECEIVED RESQUEST OR YOUR RESPONSE>
        ....
}

I provide some detailed code here

In client streaming, besides the above signal, you can check whether the server can receive the msg:

req, err := grpc.ServerStream.Recv()
if err == io.EOF {
    break
} else if err != nil {
    return err
}
like image 166
Franci Avatar answered Sep 19 '22 18:09

Franci