I’m creating a C++ class that will receive data from a socket.
I’ve been looking at Rama’s Tutorial on the matter, but it seems that some of the methods used are outdated, and aren’t easily ported to Unreal Engine 4.9.2 for someone with little experience using C++ and Unreal Engine 4.
Therefore i ask you if there is anyone who has a code sample, or any tips or tutorials on how to create a simple listener class that will receive data via sockets, that is compatible with Unreal Engine 4.9.2.
Hey guys!
We used Rama’s tutorial as well, and it works just fine. We’re running it in 4.10.
In the listener, however, when receiving data in the while loop, you set the size of the ReceivedData-array. Rama’s tutorial shows this line:
ReceivedData.Init(FMath::Min(Size, 65507u));
Which - if I remember correctly - is to be deprecated.
Replacing it with:
ReceivedData.SetNum(Size);
Works fine.
Just follow Rama’s tutorial - it works (he’s a genius).
Another tip is that when you finally get it working, I’d strongly suggest you use FMemoryReader & FMemoryWriter to read and write to the byte array. Rama has written a tutorial on that subject as well.
It’s incredibly easy to use and helps a bunch.
For example, if you use OpCodes in your packets and know what you’re about to receive, you can just start extracting the data from your byte array.
If you finally get an ISocketSubsystem instance working, here’s a code example for the actual socket list that might help:
void UDatabaseServerConnection::ReadFromSocket() {
TArray<uint8> ReceivedData;
uint32 Size;
while(DBMainSocket->HasPendingData(Size)) {
/* DBMainSocket = Our ISocketSubsystem instance */
/* HasPendingData function writes to Size the number of bytes we have pending in the socket */
ReceivedData.SetNum(Size);
/* We set the size of our "read bytes" array to Size, so it has room for the pending bytes */
int32 Read = 0;
DBMainSocket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
/* Recv writes to ReceivedData */
/* Read = The number of bytes read from function Recv, info you can use for other purposes ( we don't, at the moment) */
}
FMemoryReader DataReader = FMemoryReader(ReceivedData);
uint8 OpCode = 0;
DataReader << OpCode; // <-- This is why we use FMemoryReader, easy to use! :D
/* OpCode = The first byte in the packet, since the size of uint8 is one byte*/
switch(OpCode) {
/* Identify the type of packet received via OpCode and read the rest of the data accordingly */
}