1. 安装grpc

  1. go get -u google.golang.org/grpc

2. 服务端 server

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/youzeliang/gopractice/grpcfor/example"
  6. "google.golang.org/grpc"
  7. "log"
  8. "net"
  9. "strconv"
  10. )
  11. var times = 0
  12. type service struct {
  13. }
  14. func (s *service) HelloWorld(ctx context.Context, in *example.HelloRequest) (*example.HelloReply, error) {
  15. log.Printf("Received: %v", in.Name)
  16. times++
  17. return &example.HelloReply{Message: "Hello 您好!" + in.Name+" 您是今天第"+strconv.Itoa(times)+"个访客"}, nil
  18. }
  19. func main() {
  20. conn, err := net.Listen("tcp", "127.0.0.1:9999")
  21. fmt.Println(conn, err)
  22. server := grpc.NewServer()
  23. example.RegisterHelloServer(server, &service{})
  24. //读取请求并响应
  25. err = server.Serve(conn)
  26. if err != nil {
  27. log.Fatalf("failed to serve: %v", err)
  28. }
  29. }

3. 客户端

  1. package main
  2. import (
  3. "context"
  4. "google.golang.org/grpc"
  5. "log"
  6. "os"
  7. pb "github.com/youzeliang/gopractice/grpcfor/example"
  8. "time"
  9. )
  10. func main() {
  11. //连接服务端句柄
  12. //WithInsecure()不指定安全选项
  13. conn, err := grpc.Dial("127.0.0.1:9999", grpc.WithInsecure())
  14. if err != nil {
  15. log.Fatalf("did not connect: %v", err)
  16. }
  17. defer conn.Close()
  18. cli := pb.NewHelloClient(conn)
  19. name := "XXGH"
  20. //获取命令行参数
  21. if len(os.Args) > 1 {
  22. name = os.Args[1]
  23. }
  24. //设置上下文超时
  25. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  26. defer cancel()
  27. //响应
  28. resp, err := cli.HelloWorld(ctx, &pb.HelloRequest{Name: name})
  29. if err != nil {
  30. log.Fatalf("could not succ: %v", err)
  31. }
  32. log.Printf("Receive from server: %s", resp.Message)
  33. }