如何在协议缓冲区中表示二维数组?

时间:2018-08-17 14:52:00

标签: protocol-buffers grpc

例如:

[[1,2],[3,4]...]

我只是想测试RPC是否支持二维数组,但是出了点问题,我在关注官方文档。

服务器如下:

data = [[i, 9] for i in range(128)]


class Greeter(hello_pb2_grpc.GreeterServicer):

    def SayHello(self, request, context):
        return hello_pb2.HelloReply(results=data)


def serve():

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options=[
                     (cygrpc.ChannelArgKey.max_send_message_length, -1),
                     (cygrpc.ChannelArgKey.max_receive_message_length, -1)
      ])
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50052')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

客户端如下:

def insecure_channel(host, port):
        channel = grpc.insecure_channel(
            target=host if port is None else '%s:%d' % (host, port),
            options=[(cygrpc.ChannelArgKey.max_send_message_length, -1),
                     (cygrpc.ChannelArgKey.max_receive_message_length, -1)])
        return grpc.beta.implementations.Channel(channel)

def run():
    channel = grpc.insecure_channel('localhost:50052')
    stub = hello_pb2_grpc.GreeterStub(channel)
    st = time.time()
    response = stub.SayHello(hello_pb2.HelloRequest(name='test'))
    et = time.time() - st
    print("Greeter client received: {}, {}".format(type(response.results), et))


if __name__ == '__main__':
    run()

protobuf定义如下

syntax = "proto3";

package hello;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
    repeated Result results = 1;
}

message Result {
    repeated int32 index = 1;
    repeated int32 count = 2;
}

但是我得到这样的错误:

  File "greeter_server.py", line 19, in SayHello
    return hello_pb2.HelloReply(results=data)
TypeError: Parameter to MergeFrom() must be instance of same class: expected hello.Result got list.

我正在使用python3。

谢谢。

2 个答案:

答案 0 :(得分:0)

根据您的问题,[[1,2],[3,4]...]是一个数组数组。

这样的事情应该可以解决您的问题

message InternalArray {
    repeated int internal_array = 1;
}
repeated internal_array array = 1;

答案 1 :(得分:0)

问题是您希望在hello.Result处传递的列表。

使用:

    import hello_pb2
    to_return = hello_pb2.Result()
    to_return.index = 111
    to_return.count = 222
现在从rpc调用返回`to_return`。