golang grpc.
生成:
protoc --go_out=plugins=grpc:. helloworld.proto
go build -mod=vendor -o sers server/main.go
go build -mod=vendor -o cli client/main.go
SERVER:
package main
import (
"log"
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "grpc/protocol/test_protocol"
)
const (
PORT = ":50001"
)
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) TestingFun(ctx context.Context, in *pb.TestRequest) (*pb.TestReply, error) {
log.Println("request: ", in.Name)
return &pb.TestReply{Message: "Hello " + in.Name}, nil
}
func main() {
lis, err := net.Listen("tcp", PORT)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterTestclassServer(s, &server{})
log.Println("rpc服务已经开启")
s.Serve(lis)
}
CLENT:
package main
import (
"log"
"os"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "grpc/protocol/test_protocol"
)
const (
address = "localhost:50001"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewTestclassClient(conn)
name := "lin"
if len(os.Args) > 1 {
name = os.Args[1]
}
r, err := c.TestingFun(context.Background(), &pb.TestRequest{Name: name})
if err != nil {
log.Fatalf("could not greetss: %v", err)
}
log.Println(r.Message)
}