Sending a data buffer through a TCP connection

Good evening,

to send some measured data I have to put values into an array together with the timestamps. The values and stamps differ in length and signedness. How should I properly put them together into one array and receive this array with a TCP socket?
On the receiving side I'm working with the recv() function from winsock2.h and on the sending side my microcontroller tries to send through Server.write().

Code snippet from the sending side:

//example values. t can get really big
int32_t num0 = 1328;
int32_t num1 = 2222;
uint64_t tv = 100;

uint64_t buffer[3];
buffer[0] = num0;
buffer[1] = num1;
buffer[2] = tv;

server.write((uint8_t*)  buffer, 4);

On the receiving side I tried solutions based on the answers to my previous post

For example something like this after calling recv():

uint64_t x = ((uint64_t) buffer[0] << 0)
                | ((uint64_t) buffer[1] << 8)
                | ((uint64_t) buffer[2] << 16)
                | ((uint64_t) buffer[3] << 24);

    uint32_t y = ((uint32_t) buffer[4] << 0)
                | ((uint32_t) buffer[5] << 8)
                | ((uint32_t) buffer[6] << 16)
                | ((uint32_t) buffer[7] << 24);

    uint32_t z = ((uint32_t) buffer[8] << 0)
                | ((uint32_t) buffer[9] << 8)
                | ((uint32_t) buffer[10] << 16)
                | ((uint32_t) buffer[11] << 24);

I get garbage with this. Do I have to shift the bytes from the array position 8 - 11 to the front and so on, like in the following answer from blh64?

And how to receive arrays with more than 100 values? Do they all have to be shifted? Wouldn't that be a huge amount of code just shifting?

That does not make sense. If buffer is of type uint64_t, then each value consumes 4 bytes of memory so your .write() is only sending buffer[0] which would be num0

Edit: uint64_t is 8 bytes long, not 4 :slight_smile:

So Server.write() has to be called multiple times?

I've tried calling server.write() multiple times but it didn't work. Now I've tried it again and it works :grinning_face_with_smiling_eyes:

if each value in buffer is 8 bytes (not 4 like I originally said) and you want to send 3 of those values, that would be 8 * 3 = 24 bytes

server.write((uint8_t*) buffer, sizeof(buffer));
1 Like

It seems to kinda work with sizeof(buffer) too, thank you.
But somehow my value num1 doesn't make it to the receiver and I get nulls there. I'll try some things :blush:

EDIT: It's just like blh64 said. uint64_t is 8 bytes long and so the receiving side can't expect to get 4 bytes long data. There are nulls filling up the unused bytes in the data and this has to be taken care of on the receiving side.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.