1 py服务端, go客户端
(1) helloworld.proto
syntax = "proto3";option go_package = "./;proto";service Greeter {rpc SayHello (HelloRequest) returns (HelloReply);}message HelloRequest {string name = 1;}message HelloReply {string message = 1;}
根据proto文件生成py文件
python -m grpc_tools.protoc -I . —python_out=. —grpc_python_out=. helloworld.proto 上面可能等价于 protoc —python_out=./ —python-grpc_out=./ helloworld.proto
修改生成的helloworld_pb2_grpc.py
import helloworld_pb2 as helloworld__pb2改为from . import helloworld_pb2 as helloworld__pb2
(2) server.py
from concurrent import futuresimport grpcfrom proto import helloworld_pb2, helloworld_pb2_grpcclass Greeter(helloworld_pb2_grpc.GreeterServicer):def SayHello(self, request, context):return helloworld_pb2.HelloReply(message=f"你好, {request.name}")if __name__ == '__main__':server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)server.add_insecure_port('127.0.0.1:65432')server.start()server.wait_for_termination()
(3) client.go
package mainimport ("context""fmt""google.golang.org/grpc""grpc_test/proto")func main() {conn, err := grpc.Dial("127.0.0.1:65432", grpc.WithInsecure())if err != nil {panic(err)}defer conn.Close()c := proto.NewGreeterClient(conn)r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "bobby"})if err != nil {panic(err)}fmt.Println(r.Message)}
2 go服务端, py客户端
(1) helloworld.proto
syntax = "proto3";option go_package = "./;proto";service Greeter {rpc SayHello (HelloRequest) returns (HelloReply);}message HelloRequest {string name = 1;}message HelloReply {string message = 1;}
根据proto文件生成go文件
protoc -I ./ helloworld.proto —go_out=plugins=grpc:.
(2) server.go
package mainimport ("context""fmt""google.golang.org/grpc""grpc_test/proto""net")type Server struct {}func (s *Server) SayHello(ctx context.Context,request *proto.HelloRequest) (*proto.HelloReply, error){return &proto.HelloReply{Message: "hello," + request.Name,}, nil}func main() {g := grpc.NewServer()proto.RegisterGreeterServer(g, &Server{})lis, err := net.Listen("tcp", fmt.Sprintf(":8080"))if err != nil {panic("failed to listen: " + err.Error())}_ = g.Serve(lis)}
