grpc go安装教程
安装protobuf go get -u github.com/golang/protobuf/proto go get -u github.com/golang/protobuf/protoc-gen-go 此时会生成protoc-gen-go,protoc一般是获取已经编译好的可执行文件(https://github.com/google/protobuf/releases) 安装gRPC go get -u google.golang.org/grpc 不过由于国内的网络原因上面的命令可能不会成功 执行下面的多条命令来代替 git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net 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("%sn",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:57501n") 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("%sn",string(r.Data)) 18 } 使用go build -o client HelloService.pb.go client.go编译 C++版本的服务器 Go客户端 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |