安裝protobuflinux
go get -u github.com/golang/protobuf/protogit
go get -u github.com/golang/protobuf/protoc-gen-gogithub
此時會生成protoc-gen-go,protoc通常是獲取已經編譯好的可執行文件(https://github.com/google/protobuf/releases)golang
linux須要將protoc-gen-go放到/usr/bin/,windows由於$GOPATH/bin已經加到PATH中了因此能夠直接找到windows
安裝gRPC服務器
go get -u google.golang.org/grpc網絡
不過因爲國內的網絡緣由上面的命令可能不會成功tcp
執行下面的多條命令來代替測試
git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/netui
git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text
git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
若是 $GOPATH中有多個路徑,請手動替換成其中一個。
測試案例
HelloService.proto和以前C++編譯教程的同樣
生成命令以下:
protoc HelloService.proto -I . --go_out=. 這個是僅僅生成protobuf的產物
protoc HelloService.proto -I . --go_out=plugins=grpc:.
生成的HelloService.pb.go 須要改爲package main
server.go
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "net" 7 8 "google.golang.org/grpc" 9 ) 10 11 type HelloServiceServerImpl struct { 12 } 13 14 func (s *HelloServiceServerImpl) SayHello(c context.Context, req *Request) (*Response, error) { 15 fmt.Printf("%s\n", string(req.Data)) 16 17 resp := Response{} 18 resp.Data = []byte("hello from server") 19 20 return &resp, nil 21 } 22 23 func main() { 24 lis, err := net.Listen("tcp", "127.0.0.1:57501") 25 if err != nil { 26 fmt.Println(err) 27 return 28 } 29 s := grpc.NewServer() 30 RegisterHelloServiceServer(s, &HelloServiceServerImpl{}) 31 fmt.Printf("Server listening on 127.0.0.1:57501\n") 32 s.Serve(lis) 33 }
client.go
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "google.golang.org/grpc" 8 ) 9 10 func main() { 11 conn, err := grpc.Dial("127.0.0.1:57501", grpc.WithInsecure()) 12 if err != nil { 13 fmt.Println(err) 14 } 15 client := NewHelloServiceClient(conn) 16 r, err := client.SayHello(context.Background(), &Request{Data: []byte("send from client")}) 17 fmt.Printf("%s\n", string(r.Data)) 18 }
使用go build -o client HelloService.pb.go client.go編譯
C++版本的服務器
Go客戶端