How to receive both json format and binary data successively from a TCP/IP socket?

Viewed 28

I have a protocol that if a json message has a top-level key called "the_key", then after the json message, a binary data set will be transmitted. An example of the protocol is as follows:

The server:

length_of_the data = 500000
msg = {'the_key': {'len': length_of_the_binary, 'Indices': [0, 1000, 4000, 5000], 'Type':'float32'}}
data = np.random.rand(length_of_the_data).astype(np.float32)

# Create a socket object
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:

    sock.connect((HOST, PORT))

    # send first the length of the data
    sock.sendall(bytes(json.dumps(msg), encoding="utf-8"))

    # send the data
    sock.sendall(data.tobytes(order='C'))

There are other json messages sending through the socket with different top-level keys. Is there a good way to receive both the json message and the binary data at the client?

0 Answers
Related