UDP UE4 Client

Hello All:

Im looking for a bit of help. I have a UDP chat server from a previous project that Id like to use with UE4.

Before i go re-inventing the wheel, does anyone have a UDP client written that wouldnt mind sharing the code, or can someone please point me in the right direction.

thanks!

Here’s how you can connect to a UDP server using FSocket:



#include "SocketSubsystem.h"
#include "Sockets.h"
#include "Networking.h"

...
	const FIPv4Address IP(127, 0, 0, 1);
	const int32 Port = 80;

	TSharedRef<FInternetAddr> Addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
	Addr->SetIp(IP.GetValue());
	Addr->SetPort(Port);

	FSocket* Socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream, TEXT("Socket"), false);
	bool Connected = Socket->Connect(*Addr);


You will have to add “Sockets” (and maybe “Networking”) to your PublicDependencyModules in your project’s MyGame/Source/MyGame/MyGame.Build.cs:



	PublicDependencyModuleNames.AddRange(new string] { "Core", "CoreUObject", "Engine", "InputCore", "Sockets", "Networking" });


You can FSocket::Send and FSocket::Recv to send and receive byte arrays. Although Send/Recv have a uint8* as type for the data buffer, you can also pass a TArray argument which is easier to work with.

To convert your custom data (ints, strings, floats, etc) into bytes, or parse incoming data from bytes, you can use reinterpret_cast:



TArray<uint8> OutData;
const int32 ExampleValue = 1337;
const uint8 * Bytes = reinterpret_cast<const uint8*>(&ExampleValue);
for (int i = 0; i < 4; ++i) // int = 4 bytes
	OutData.Add(Bytes*);


Hope that helps. :slight_smile: