I am working on a school project where I am communicating with an embedded chip via a short Python script that looks like this:
send = ''
receive = ''
send = input()
data = [int(send), int(2)]
print(int(send).to_bytes(1, 'big'))
encoded_data = struct.pack('>{}B'.format(len(data)), *data)
print(encoded_data)
s.send(encoded_data)
sleep(0.1)
receive = s.recv(1024).decode('UTF-8','ignore').strip()
print(receive, end = '\n')
I would like to translate this code into C++ to use in a larger piece of software. I started using Winsock2 and I have managed to establish a TCP connection and send/ receive data, but it's all mumbo jumbo when receiving (expected), because I do none of the special pre- & post-processing that I did in Python, rather I am just:
void send_message(const char *payload) {
send(socket, payload, strlen(payload), 0);
}
...
std::string receive() {
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
int n = recv(socket, buffer, 1024, 0);
if (n < 0) {
error("Lost connection");
}
return buffer;
}
For sending, as far as I understand, the Python script is taking the console input and converting it to integers (ASCII), then creating an array that has two elements: the message, and the integer 2, packing that into a structure, formatted as a big-endian unsigned chars. How exactly can I do the same in C++? Do I need to create space in memory and memcpy an identical C++ struct into it? How will I assure the endianess will be respected? Side note, this code will only run on a Windows 10 64-bit machine.
For receiving, I see that the bytes received are in UTF-8 format and then they are decoded. I am planning on adding Boost to this project so I can handle the UTF-8 strings in a very elegant manner. Is this a good idea?
Edit
I see now that UTF-8 is backwards-compatible with ASCII so there's no need to do anything special when receiving, maybe writing something to remove the leading and trailing spaces from the message, just like .strip().