1

目录结构

└── study
    └── rpc
        ├── c.go(客户端)
        ├── lib
        │   ├── test.pb.go(这个文件是protoc生成的)
        │   └── test.proto
        └── s.go(服务端)

test.proto

syntax = "proto3";
package lib;

service Test {
  rpc Say (Request) returns (Response) {}
}

message Request {
  string name = 1;
}

message Response {
  string age = 1;
}

编译

在rpc目录下执行

protoc -I lib lib/test.proto --go_out=plugins=grpc:lib

服务端

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "net"
    "study/rpc/lib"
)

type server struct {
    lib.UnimplementedTestServer
}

func (s *server) Say(ctx context.Context, in *lib.Request) (*lib.Response, error) {
    fmt.Println(in.GetName())
    return &lib.Response{Age: in.GetName()}, nil
}

func main() {
    l, _ := net.Listen("tcp", ":10000")
    s := grpc.NewServer()
    lib.RegisterTestServer(s, &server{})
    s.Serve(l)
}

客户端

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "time"
    "study/rpc/lib"
)

func main() {
    conn, _ := grpc.Dial(":10000", grpc.WithInsecure(), grpc.WithBlock())
    defer conn.Close()
    c := lib.NewTestClient(conn)
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    r, _ := c.Say(ctx, &lib.Request{Name: "c"})
    fmt.Println(r.GetAge())
}

xxfaxy
1.6k 声望18 粉丝