1

I hope the client can detect that the server is closed without sending any request, so I use the keepalive option. But when I shutdown the server with ctrl+c, the connectvity state in client just turn from ready to idle instead of shutdown.

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "google.golang.org/grpc/connectivity"
    "google.golang.org/grpc/keepalive"
    "log"
    "sync"
    "time"
)
func main() {

    var kap = keepalive.ClientParameters{
        Time:                15 * time.Second, // send pings every 10 seconds if there is no activity
        Timeout:             time.Second,      // wait 1 second for ping ack before considering the connection dead
        PermitWithoutStream: true,             // send pings even without active streams
    }
    conn, err := grpc.Dial(
        "localhost:50051",
        grpc.WithBlock(),
        grpc.WithInsecure(),
        grpc.WithKeepaliveParams(kap),
    )
    if err != nil {
        log.Fatalf("failed to dial: %v", err)
    }
    log.Println(conn.GetState())  
    wg := sync.WaitGroup{}
    wg.Add(1) 
    go func() {
        for {
            log.Println(conn.GetState())
            if conn.WaitForStateChange(context.Background(), conn.GetState()) {
                if conn.GetState() == connectivity.Shutdown {
                    log.Println("connection closed")
                    // TODO:
                    break
                }
            }
        }
        defer wg.Done()
    }()
    // wait
    wg.Wait()
    fmt.Println("gRPC connection closed")
}

I expect that the client can detect that the server closed in the grpc streaming connection without sending any request.

  • 1
    The `Shutdown` state is only used when there has been an explicit request to close the connection client side (i.e. a call to `conn.Close()`). – nj_ Feb 21 '23 at 11:03

0 Answers0