从tcp套接字获取GPB数据,解码i

2024-06-28 20:01:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个应用程序,它通过tcp流式传输gpb数据消息。tcp头是12个字节(msg_type、encode_type、msg_version、flags、msg_length)。然后我用msg_长度得到数据。在

import json
import logging
from tornado.tcpserver import TCPServer
from tornado.iostream import StreamClosedError
from tornado import gen
from tornado.ioloop import IOLoop
from struct import Struct, unpack
from telemetry_pb2 import Telemetry

class TelemetryServer(TCPServer):
    def __init__(self):
        super().__init__()
        self.header_size = 12
        self.header_struct = Struct('>hhhhi')
        self._UNPACK_HEADER = self.header_struct.unpack

    @gen.coroutine
    def handle_stream(self, stream, address):
        print(f"Got connection from {address}")
        while not stream.closed():
            try:
                header_data = yield stream.read_bytes(self.header_size)
                msg_type, encode_type, msg_version, flags, msg_length = self._UNPACK_HEADER(header_data)
                encoding = {1:'gpb', 2:'json'}[encode_type]
                msg_data = b''
                print(encode_type)
                if encode_type == 1:
                    print(f'Got {msg_length} bytes from {address} with encoding {encoding}')
                    while len(msg_data) < msg_length:
                        packet = yield stream.read_bytes(msg_length - len(msg_data))
                        msg_data += packet
                    print(msg_data)
                    gpb_parser =Telemetry()
                    gpb_data = gpb_parser.ParseFromString(msg_data.decode('ascii'))
                    print(gpb_data.node_id)
                else:
                    print(f'Got {msg_length} bytes from {address} with encoding {encoding}')
                    while len(msg_data) < msg_length:
                        packet = yield stream.read_bytes(msg_length - len(msg_data))
                        msg_data += packet
                    json_data = json.loads(msg_data.decode("ascii"))
            except Exception as e:
                print(e)
                stream.close()



def main():
    server = TelemetryServer()
    server.bind(5556)
    server.start(0)
    IOLoop.current().start()

我得到的错误是数据是python字节字符串

^{pr2}$

问题是如何将这个字节字符串转换成字符串以便进行解析?在

解决了:

遥测对象不是解析器,而是完整的消息对象。所以可以

gpb_parser =Telemetry()
gpb_parser.ParseFromString(msg_data)
print(gpb_parser.node_id)

Tags: fromimportselfparserdatastreambytestype