erling erling - 2 months ago 13x
C++ Question

Python socket receive and store data

I have set up a socket between a C++ program and a python script. Its all very simple, I want to send coordinates at approx 20 Hz from the C program to Python. This is just a first try and I want to send one set of coordinates, it looks like this:

C++ program, the server:

struct coord {
int x;
int y;
int z;

struct coord co;

co.x = 1;
co.y = 2;
co.z = 3;

char *msg;
msg = (char*) &co;

send(newsockfd, msg,strlen((char*) &co), 0);

This is the important part, I have before this successfully initialized a socket with a specific address. Now I want to send these three coordinates to the python program. I send the address to the first integer(co.x), and the the allocated memory, which should be 12 bytes.

This is the python script. Again I have only included the important stuff.

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
recvInt = sock.recv(4096)

Now I want to access the first 4 bytes and store the in a variable, and the next 4 in a separate and the last 4 in a third variable. But how do I do this? recvInt is this, seemingly, useless object Bytes, I haven't manage to convert it to anything and the printouts doesn't give any sense either. Could someone please help me or point me in the right direction?

EDIT: When I do a printout of: type(recvInt) it says that its a str. That is also weird considering the documentation of the function socket.recv() which clearly states that it returns a Bytes. However, now I also find documentation that this function should return a string representation of the data. Which is correct? And this supposed string representation is just a little box with four digits, looks like a visual representation of a byte. However msg contains 12 bytes, and there's no indexing on recvInt.
Thank you


Take a look at the struct library for python.

Essentially, for your situation, something like the following might work.

import struct

x, y, z = struct.unpack("!iii", receivedData)

The above code will parse the received string into 3 signed integers.

socket.recv returns a binary string which is essentially a byte array. Rather than have separate functions for recvInt or parseInt, Python provides a library to parse an arbitrary binary string into different sized integers or strings.