1 py服务端, go客户端

(1) helloworld.proto

  1. syntax = "proto3";
  2. option go_package = "./;proto";
  3. service Greeter {
  4. rpc SayHello (HelloRequest) returns (HelloReply);
  5. }
  6. message HelloRequest {
  7. string name = 1;
  8. }
  9. message HelloReply {
  10. string message = 1;
  11. }

根据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

  1. import helloworld_pb2 as helloworld__pb2
  2. 改为
  3. from . import helloworld_pb2 as helloworld__pb2

(2) server.py

  1. from concurrent import futures
  2. import grpc
  3. from proto import helloworld_pb2, helloworld_pb2_grpc
  4. class Greeter(helloworld_pb2_grpc.GreeterServicer):
  5. def SayHello(self, request, context):
  6. return helloworld_pb2.HelloReply(message=f"你好, {request.name}")
  7. if __name__ == '__main__':
  8. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  9. helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
  10. server.add_insecure_port('127.0.0.1:65432')
  11. server.start()
  12. server.wait_for_termination()

(3) client.go

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc"
  6. "grpc_test/proto"
  7. )
  8. func main() {
  9. conn, err := grpc.Dial("127.0.0.1:65432", grpc.WithInsecure())
  10. if err != nil {
  11. panic(err)
  12. }
  13. defer conn.Close()
  14. c := proto.NewGreeterClient(conn)
  15. r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "bobby"})
  16. if err != nil {
  17. panic(err)
  18. }
  19. fmt.Println(r.Message)
  20. }

2 go服务端, py客户端

(1) helloworld.proto

  1. syntax = "proto3";
  2. option go_package = "./;proto";
  3. service Greeter {
  4. rpc SayHello (HelloRequest) returns (HelloReply);
  5. }
  6. message HelloRequest {
  7. string name = 1;
  8. }
  9. message HelloReply {
  10. string message = 1;
  11. }

根据proto文件生成go文件

protoc -I ./ helloworld.proto —go_out=plugins=grpc:.

(2) server.go

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc"
  6. "grpc_test/proto"
  7. "net"
  8. )
  9. type Server struct {}
  10. func (s *Server) SayHello(ctx context.Context,
  11. request *proto.HelloRequest) (*proto.HelloReply, error){
  12. return &proto.HelloReply{
  13. Message: "hello," + request.Name,
  14. }, nil
  15. }
  16. func main() {
  17. g := grpc.NewServer()
  18. proto.RegisterGreeterServer(g, &Server{})
  19. lis, err := net.Listen("tcp", fmt.Sprintf(":8080"))
  20. if err != nil {
  21. panic("failed to listen: " + err.Error())
  22. }
  23. _ = g.Serve(lis)
  24. }