UDP RecvFrom Using FSocket

Is UDP receive with FSocket currently working? I’ve been trying several different UDP socket setups with general & specific IP/port settings for both socket creation and the RecvFrom address; I can’t get any data on the socket no matter what. I know that my test data is going to the correct IP & port (checked it with Wireshark), but HasPendingData() always indicates an empty socket.

Socket setup

FIPv4Endpoint Endpoint(FIPv4Address::Any, 9001);
FSocket *ReceiverSocket = FUdpSocketBuilder(*SocketName)
    .AsNonBlocking()
    .AsReusable()
    .BoundToEndpoint(Endpoint)
    .WithReceiveBufferSize(2 * 1024 * 1024);

RecvFrom call (in a timer function)

TSharedRef<FInternetAddr> targetAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();

TArray<uint8> ReceivedData;

uint32 Size;
while (ReceiverSocket->HasPendingData(Size))
{
    ReceivedData.SetNumUninitialized(FMath::Min(Size, 65507u));

    int32 Read = 0;
    ReceiverSocket->RecvFrom(ReceivedData.GetData(), ReceivedData.Num(), Read, *targetAddr);
}

One thing odd I noticed is that, according to netstat, the UE4 Editor is opening a UDP socket on my receiver’s port as soon as the Editor loads my project. It creates the one I expected once I start the game (my receiver class is spawned in GameMode’s constructor). The socket created in GameMode is cleaned up when I exit the game, but the Editor-created one doesn’t close until I close the Editor.

1 Like

Bump for help

Finally figured it out, don’t try to call any socket-creation functions from UDP receiver class’s constructor. That’s what created the socket as soon as I loaded my project and then it ran the code again when the game started. Trying to bind another socket while running the game failed because the address was already in use. I moved my creation function calls to the receiver’s BeginPlay() and it all started working.

Not sure if executing the class constructor code before actually starting the game is Working As Intended or a bug, but at least now I know it happens.

1 Like