2016-12-15 54 views
1

下午好。Google Protobuf - C++和Python之間的UDP通信 - google.protobuf.message.DecodeError:解壓縮需要長度爲4的字符串參數

我想在CPP中的一個框架和Python中的另一個框架之間發送消息。我遵循了同樣的過程中顯示: Serialize C++ object to send via sockets to Python - best approach?

在Python我的服務器代碼:

import socket 
from DiceData_pb2 import DiceData 

UDP_PORT=1555 

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
sock.bind(("", UDP_PORT)) 

dicedata = DiceData() 
while True: 
    data, addr = sock.recvfrom(1024) 
    print data 
    dicedata.ParseFromString(data) 
    print ("gyrox = {0}".format(dicedata.gyrox)) 
    print("gyroy = {0}".format(dicedata.gyrox)) 
    print("gyroz = {0}".format(dicedata.gyroz)) 
    print("accelx = {0}".format(dicedata.accelx)) 
    print("accely = {0}".format(dicedata.accely)) 
    print("accelz = {0}".format(dicedata.accelz)) 
    print("roll = {0}".format(dicedata.roll)) 
    print("pitch = {0}".format(dicedata.pitch)) 
    print("yaw = {0}".format(dicedata.yaw)) 
    print("side = {0}".format(dicedata.side)) 
    print("certainty = {0}".format(dicedata.certainty)) 
    print("time = {0}".format(dicedata.time)) 

的.proto文件如下:

package prototest; 

message DiceData { 
    required float gyrox = 1; 
    required float gyroy = 2; 
    required float gyroz = 3; 
    required float accelx = 4; 
    required float accely = 5; 
    required float accelz = 6; 
    required float roll = 7; 
    required float pitch = 8; 
    required float yaw = 9; 
    required int32 side = 10; 
    required float certainty = 11; 
    required string time = 12; 
} 

我知道的通信工作,因爲服務器收到第一條消息並將其打印爲垃圾。然而,到達ParseFromString行之後,下面的錯誤發生:

Traceback (most recent call last): 
    File "server.py", line 13, in <module> 
    dicedata.ParseFromString(data) 
    File "/usr/local/lib/python2.7/dist-packages/google/protobuf/message.py", line 185, in ParseFromString 
    self.MergeFromString(serialized) 
    File "/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/python_message.py", line 1095, in MergeFromString 
    raise message_mod.DecodeError(e) 
google.protobuf.message.DecodeError: unpack requires a string argument of length 4 

有誰知道我怎麼能解決這個問題?我知道該字符串不是空的,因爲在前一行中有垃圾被打印,但我似乎無法將字符串轉換回數據結構。

回答

3

您鏈接的問題中的C++代碼已損壞。它包含此行:

sendto(sock, buf.data(), strlen(buf.c_str()), 0, (struct sockaddr *)&addr, sizeof(addr)); 

這是錯誤!它將在第一個零值字節處切斷消息。它應該是這樣的,而不是:

sendto(sock, buf.data(), buf.size(), 0, (struct sockaddr *)&addr, sizeof(addr)); 

這肯定會導致您所看到的錯誤。

我編輯了其他問題來添加此修復程序。

相關問題