TCP Data Receiver

I am trying to receive data in UE5 from .net application. I have tried the old code from the forum here but either they give some weird errors or Unreal just decides to crash.

I am able to establish connection between unreal and my application. But I never receives data ListenerSocket->HasPendingData(data) always return false.

I am writing my code here. Someone please help me in fixing this issue.

if (ListenerSocket)
{
    // Handle incoming connections or data here
    // Example: Use ListenerSocket->Recv() to receive data
    // Check for incoming connections
    uint32 data = 0;
    FSocket* NewConnection = ListenerSocket->Accept("NewConnection");
    if (NewConnection != nullptr)
    {
        // New connection established
        UE_LOG(LogTemp, Warning, TEXT("New Connection Established"));
        if (ListenerSocket->HasPendingData(data))
        {
            UE_LOG(LogTemp, Warning, TEXT("HasPendingData: true: %s"), data);
        }
        else
        {
            UE_LOG(LogTemp, Warning, TEXT("HasPendingData: false"));
        }
        // Close the new connection for now (you may want to keep it open for communication)
        NewConnection->Close();
        ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(NewConnection);
    }

    // Check for incoming data
    // Receive data
    int32 BytesRead = 0;

    // Resize the buffer to accommodate the incoming data
    ReceivedDataBuffer.SetNumUninitialized(1024); // Adjust the size as needed

    // Receive data into the buffer
    int32 Read = 0;
    if (ListenerSocket->Recv(ReceivedDataBuffer.GetData(), ReceivedDataBuffer.Num(), Read))
    {
        UE_LOG(LogTemp, Warning, TEXT("if ...New Connection Established"));
        // Handle the received data
        if (Read > 0)
        {
            ReceivedDataBuffer.SetNum(Read); // Resize to the actual received size
            HandleReceivedData(ReceivedDataBuffer);
        }
    }
    else
    {
        // Error handling
        const FString SocketError = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->GetSocketError();
        if (!SocketError.IsEmpty())
        {
            UE_LOG(LogTemp, Error, TEXT("Error receiving data: %s"), *SocketError);
        }
        else
        {
            UE_LOG(LogTemp, Error, TEXT("Error receiving data. Unknown socket error."));
        }
    }

Also I am new to Unreal Engine, pardon me for stupid question.

Thanks

I got it working!

1 Like

How would u be able explain?