我正在尝试使用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文件)。但我这里什么也没有得到。当我在没有使用Trio的脚本中运行时,Dtc.EncodingResponse()
可以以可读格式完整地返回响应。
我猜问题可能出在 "client_stream" 是一个Trio流对象,只能读取字节,所以我可能需要使用 ReceiveChannel
对象来代替。但如果是这样,我不知道该怎么做。
更新:Nathaniel J. Smith 给出的下面答案解决了我的问题。
m_resp = Dtc.EncodingResponse()
m_resp.ParseFromString(m_body)
我觉得自己很傻,之前没有对数据进行ParseFromString处理,这就是问题所在。非常感谢所有回复我的人,希望这能帮助到其他人。
# encoding request
开头的代码行的缩进会破坏代码。名称client_stream
是在parent
协程的本地范围内创建的,但现在在其外部被使用。此外,以parent:
开头的print
有些暗示这仍应该是coro主体的一部分。您能验证一下吗? - shmee