我正在尝试在 python 中使用 protobuf 读取一些数据流,并且我想使用 trio 使客户端用于读取流。protobuf 有一些方法调用,当我使用 trio 流时,我发现它们不起作用。
Linux 机器上的 Python 客户端。
import DTCProtocol_pb2 as Dtc
async def parent(addr, encoding, heartbeat_interval):
print(f"parent: connecting to 127.0.0.1:{addr[1]}")
client_stream = await trio.open_tcp_stream(addr[0], addr[1])
# encoding request
print("parent: spawing encoding request ...")
enc_req = create_enc_req(encoding) # construct encoding request
await send_message(enc_req, Dtc.ENCODING_REQUEST,client_stream, 'encoding request') # send encoding request
log.debug('get_reponse: started')
response = await client_stream.receive_some(1024)
m_size = struct.unpack_from('<H', response[:2]) # the size of message
m_type = struct.unpack_from('<H', response[2:4]) # the type of the message
m_body = response[4:]
m_resp = Dtc.EncodingResponse()
m_body
将是一些字节数据,我不知道如何解码。Dtc.EncodingResponse()
是 protobuf 方法,它会给出一个包含可读格式响应的 Dtc 对象。(Dtc 是 protobuf 文件)。但我在这里什么也得不到。当我在没有三重奏的情况下执行此脚本时,Dtc.EncodingResponse()
将以可读的格式给出完整的响应。
我猜问题是“client_stream”是一个只读取字节的三重流对象,所以我可能需要使用一个ReceiveChannel
对象。但如果这是真的,我不知道该怎么做。
更新: Nathaniel J. Smith 下面的答案解决了我的问题。
m_resp = Dtc.EncodingResponse()
m_resp.ParseFromString(m_body)
我觉得很傻,但是我之前没有 ParseFromString 数据,仅此而已。非常感谢所有回复的人。希望这可以帮助那里的人。