准备工作
go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/protoc-gen-go
export PATH=$PATH:$GOPATH/bin
目录结构
.
├── Makefile
├── client/
│ └── client.go
├── helloworld/
│ ├── helloworld.pb.go
│ └── helloworld.proto
└── server/
├── Makefile
└── server.go
协议
syntax = "proto3";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
服务器端
//go:generate protoc -I ../helloworld --go_out=plugins=grpc:../helloworld ../helloworld/helloworld.proto
package main
import (
"log"
"net"
pb "simple/helloworld"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
port = ":50051"
)
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{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.RegisterGreeterServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
服务器端Makefile
BIN=server
all: ${BIN}
${BIN}:
go generate server.go
go build ${LDFLAGS} -o ${BIN} server.go
install:
go install ${LDFLAGS} -o ${BIN} server.go
clean:
if [ -f ${BIN} ]; then rm ${BIN}; fi
.PHONY: clean install
客户端
package main
import (
"context"
"log"
"google.golang.org/grpc"
pb "simple/helloworld"
)
const (
address = "localhost:50051"
defaultName = "world"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: defaultName})
if err != nil {
log.Fatal(err)
}
log.Printf("r.Message = %+v\n", r.Message)
}
客户端Makefile
BIN=client
all: ${BIN}
${BIN}:
go build ${LDFLAGS} -o ${BIN} client.go
install:
go install ${LDFLAGS} -o ${BIN} client.go
clean:
if [ -f ${BIN} ]; then rm ${BIN}; fi
.PHONY: clean install
Makefile
all:
cd server/ && ${MAKE}
cd client/ && ${MAKE}
clean:
cd server/ && ${MAKE} clean
cd client/ && ${MAKE} clean
.PHONY: clean install
编译运行
make
server/server &
client/client
# 2017/12/20 20:36:05 r.Message = Hello world