Get struct from TCP socket

Hi,
im working with Rama’s TCP code. But I want to transfer a struct which is the same for client and server.
How to do it?

Client side:

send (sock,(void*)& str_data, sizeof(str_data),0)

where str_data is the struct. It has a size of 72 bytes.
But how do I get it in unreal?
Seems like the Recv only returns uint8 pointer. How to get the struct out of it?
Any static_cast, reinterpret_cast seems to fail.

It looks like this

while(ConnectionSocket->HasPendingData(Size){
    ReceivedData.Init(FMath::Min(Size,65507u),Size);
    int32 Read = 0;
    ConnectionSocket->Recv(ReceivedData.GetData(),ReceivedData.Num(),Read);
}
// and now? it is written to ReceivedData
// StructCurrentData* str_data = (reinterpret_cast<StructCurrentData>(ReceivedData.GetData(),ReceivedData.Num()); fails...  

Any ideas how to solve it?
Thanks a lot!
L

So what should work

StructCurrentData* str_data = reinterpret_cast<StructCurrentData*>(ReceivedData.GetData(),ReceivedData.Num());

Gives me a SIGSEGV…

Hi, you can’t simply cast to the struct you want, instead, you must read data and interpret to a struct yourself. You should also keep in mind the endianness of the data you send.

HI thanks for the comment!
You mean I have to go through every byte and assign them to the struct? How to access them then?

again, thanks for the reply

Yes, that what I mean. You need to know what data you are transferring and how much does it weights. In existing protocols, you first read data that describe how further data must be read.
For example, if you send an integer value, that’s 4 bytes, and you can reconstruct it as int32 in unreal following way:

		unsigned char * bits = (unsigned char *)Buff.GetData();
		/*read little endian*/
		for (int32 n = Offset; n < Offset + 4; n++)
			result = (result << 8) + bits[n];
		Offset += 4;

An offset value is a position from where you start reading the array, if you read from start it will be 0.
Here some examples how you can read int, float, and simply data of given size.

Alright so i really have to to it bit-wise.
2 questions to it:

  1. What is Offset here?
  2. What would be a “efficent” way to send ~100 bytes every few microsecond? Always the struct and the server knows how to decrypt every message or shall i float tcp messages with every information on their own? like “coordx” “2.4” “coordy” “3.76” in 4 packages.

Thanks a lot! Really helpful :slight_smile:

An offset shows how much of data stream you had read. For example, if you read two ints (4 bytes each int) and a float(8 bytes), your offset will be 12, so you don’t read variables from the stream that you have already read.
Regardless of how you send it: full struct or small chunks(if they are in the order in which they are declared in the struct) receiving result will be the same.