首页 > 解决方案 > Python 解析来自 Web Socket 的 Protobuf 响应

问题描述

我正在使用以下原型方案与服务器交互。Python客户端 WebSocket Client用于连接。

syntax = "proto3";
package messages;
import "any.proto";

// ................................

message GeneralResponse {
    oneof response {
        MainResponseA registrationResponse = 1;
        MainResponseB connectResponse = 2;
    }
}

message MainResponseA {
    bytes bytesA = 1;
    int64 timeLeave = 2; 
}


message GeneralMessage {
    fixed32 identifier = 1;
    oneof contents {
        GeneralResponse response = 1;
        GeneralState generalState = 2;
    }
}
// ................................

在成功连接和几个请求(没问题)之后,我在相关方法中得到下一个响应on_message

@staticmethod
def on_message(ws, message):
    logging.debug("Source Message: %s \n \n", message)

    // 2) This lines parse Message and only identifier,
    //    not inner Response Objects, with other info

    gen_msg = messages.GeneralMessage()
    gen_msg.ParseFromString(message)
    logging.info('Received Msg: %s',
        gen_msg)

在源消息中,如下所示,我收到了一些大的编码消息。

    �"�R�2018 12:38:22 PM Source Message: 
    �   
    �   �PNG

    IHDRk�XTPLTE���U��~�IDATx����n$+����wg����SW"��8�YXeW#H�?J)��RJ)��RJ)��RJ)��RJ)��RJ�V����3Փϼ?��+�|<��%�U��O��\����wW�`9����Z ����X�%XH0���c��Q.L`
                                          ����VXW������CDWh�|�
    �3���$n-�io��P�fa��4�   �廖���fP���V��O�Kf�X�``
                                                    )L�����g9�����=� ��v��2w��c���( �gk��#���SVa�jc&Kp�7!~��IR�            
  // And so on ............

稍后将其解析为 Protobuf 对象后,我只有标识符!并且没有内部对象,我想在那里有字段bytesAtimeLeave. 任何想法,这里有什么问题?

07/06/2018 12:38:22 PM Received Msg: identifier: 1387340418
response {
  registrationResponse {
  }
}

标签: pythonwebsocketprotocol-buffers

解决方案


所以问题出在与服务器不同步的 Protobuf Scheme 版本中。他们在内部响应中发送了一个带有另一个字段的对象。


推荐阅读