main.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Binary client is an example client.
  19. package main
  20. import (
  21. "context"
  22. "flag"
  23. "fmt"
  24. "log"
  25. "time"
  26. "google.golang.org/grpc"
  27. pb "google.golang.org/grpc/examples/features/proto/echo"
  28. "google.golang.org/grpc/keepalive"
  29. )
  30. var addr = flag.String("addr", "localhost:50052", "the address to connect to")
  31. var kacp = keepalive.ClientParameters{
  32. Time: 10 * time.Second, // send pings every 10 seconds if there is no activity
  33. Timeout: time.Second, // wait 1 second for ping ack before considering the connection dead
  34. PermitWithoutStream: true, // send pings even without active streams
  35. }
  36. func main() {
  37. flag.Parse()
  38. conn, err := grpc.Dial(*addr, grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp))
  39. if err != nil {
  40. log.Fatalf("did not connect: %v", err)
  41. }
  42. defer conn.Close()
  43. c := pb.NewEchoClient(conn)
  44. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
  45. defer cancel()
  46. fmt.Println("Performing unary request")
  47. res, err := c.UnaryEcho(ctx, &pb.EchoRequest{Message: "keepalive demo"})
  48. if err != nil {
  49. log.Fatalf("unexpected error from UnaryEcho: %v", err)
  50. }
  51. fmt.Println("RPC response:", res)
  52. select {} // Block forever; run with GODEBUG=http2debug=2 to observe ping frames and GOAWAYs due to idleness.
  53. }