Skip to content Skip to sidebar Skip to footer

Issue Returning Header Byte From Python To Unity

I'm newbie in Python, so probably I'm wrong something. Be patient. I send JSON data from Python to Unity app. In unity I use NetworkStream and in Python I send a header before send

Solution 1:

Your Python code is... wonky. For one, you're calculating the number of keys in the dict and you're not padding the length to 5 bytes.

Assuming what you want is to send a JSON blob over the socket with an ASCII length header, you'll want

data = {'id': ...}  # Some JSONable object
json_data = json.dumps(data).encode("UTF-8")
data_len = len(json_data)
assert data_len <= 99999  # we can't represent larger length with this encoding scheme
conn.sendall(("%05d" % data_len).encode("UTF-8"))
conn.sendall(json_data)

Then on the receiving side,

var s = TcpClient.GetStream();
var header = newbyte[5];
s.Read(header, 0, header.Length);
var size = Int32.Parse(Encoding.Default.GetString(header));
var data = newbyte[size];
s.Read(data, 0, size);

should do.

However, as the assert in the Python code says, this scheme has the shortcoming that 99999 bytes is the largest blob you can send – I'd suggest sending the length as a 32-bit unsigned integer (that is, 4 binary bytes):

importstruct
# ...
conn.sendall(struct.pack("<I", data_len))  # little-endian
conn.sendall(json_data)

and

var header = newbyte[4];
s.Read(header, 0, 4);
var size = BitConverter.ToUInt32(header);
// ...

Post a Comment for "Issue Returning Header Byte From Python To Unity"