希望客户端不发送任何请求也能检测到服务器关闭,所以我使用了keepalive选项。 但是当我用 ctrl+c 关闭服务器时,客户端的连接状态只是从准备好变为空闲而不是关闭。
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")
}
我希望客户端在不发送任何请求的情况下能够检测到服务器在grpc流式连接中关闭