我的相机每5秒向我的计算机端口80发送一个带有HTTP的protobuf。我正在尝试解码protobuf消息,但它提供了google.protobuf.message.DecodeError:解析消息错误'在ParseFromString()方法中。我创建了pb2文件,打开端口,然后检查帖子是否即将发布。我相信错误的原因是我将消息读作原始而不是二进制,但我找不到任何解决方案来读取二进制或将文本转换为正确的格式。这是我的代码:
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import DevicesFrame_pb2
class S( BaseHTTPRequestHandler ):
def _set_response( self ):
self.send_response( 200 )
self.send_header( 'Content-type', 'application/octet-stream' )
self.end_headers( )
def do_POST( self ):
content_length = int( self.headers['Content-Length'] )
post_data = self.rfile.read( content_length )
devices_frame = DevicesFrame_pb2.Device( )
#Code works fine until here. Gives the error to this line
devices_frame.ParseFromString( post_data )
print( MessageToString( devices_frame ) )
self._set_response( )
def run( server_class = HTTPServer, handler_class = S, port = 80):
logging.basicConfig( level = logging.INFO )
server_address = ( '', port )
httpd = server_class( server_address, handler_class )
logging.info( 'Starting httpd....\n' )
try:
httpd.serve_forever( )
except KeyboardInterrupt( ):
pass
httpd.server_close( )
logging.info( 'Stopping httpd...\n' )
if __name__ == '__main__':
run( )