-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Open
Labels
Description
grpc-go: 1.79.2
package main
import (
"context"
"demo/msg"
"fmt"
"net"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
func main() {
c, e := grpc.NewClient("127.0.0.1:8000", grpc.WithInsecure())
if e != nil {
panic(e)
}
go func() {
time.Sleep(time.Second * 5)
cc := msg.NewMsgClient(c)
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*5))
defer cancel()
_, e := cc.Hello(ctx, &msg.HelloReq{})
if e != nil {
fmt.Println("client error:", e)
}
time.Sleep(time.Second)
}()
//server
s := grpc.NewServer()
msg.RegisterMsgServer(s, &Server{})
l, e := net.Listen("tcp", "127.0.0.1:8000")
if e != nil {
panic(e)
}
s.Serve(l)
}
type Server struct {
}
func (s *Server) Hello(ctx context.Context, req *msg.HelloReq) (*msg.HelloResp, error) {
fmt.Println("server get Hello call")
<-ctx.Done()
println("server error:", ctx.Err().Error())
return nil, status.New(400, "code=10000,msg=this is a test").Err()
}
here is the std output:
go run .\main.go
server get Hello call
server error: context canceled
client error: rpc error: code = DeadlineExceeded desc = stream terminated by RST_STREAM with error code: CANCEL
the server should get to deadline before the cancel,because of the time.sleep(time.second) in client's goroutine
Reactions are currently unavailable