Well well well guys…
I am playing around with some TCP code these days and searched the whole forums and stopped especially for Rama’s tutorials and scripts. Now there came up a question which I cannot find a solution for. Maybe I its just a error in reasoning.
Well, I am using this code, for example to send a string to my server what is working fine:
void UTCPConnection::sendPacket(){
FSocket* Socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream, TEXT("default"), false);
FString address = TEXT("127.0.0.1");
int32 port = 8000;
FIPv4Address ip;
FIPv4Address::Parse(address, ip);
TSharedRef<FInternetAddr> addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
addr->SetIp(ip.GetValue());
addr->SetPort(port);
bool connected = Socket->Connect(*addr);
FString serialized = TEXT("teststring|56");
TCHAR *serializedChar = serialized.GetCharArray().GetData();
int32 size = FCString::Strlen(serializedChar);
int32 sent = 0;
bool successful = Socket->Send((uint8*)TCHAR_TO_UTF8(serializedChar), size, sent);
}
But what if I want to receive a string back from my server ? I addad this on the bottom of my code, but its not working at all :
TArray<uint8> ReceivedData;
uint32 Size;
while (Socket->HasPendingData(Size))
{
ReceivedData.Init(FMath::Min(Size, 65507u));
int32 Read = 0;
Socket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data Read! %d"), ReceivedData.Num()));
}
Same problem here without sending data:
bool UTCPConnection::Connect(){
Socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream, TEXT("default"), false);
FString address = TEXT("127.0.0.1");
int32 port = 8000;
FIPv4Address::Parse(address, ip);
TSharedRef<FInternetAddr> addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
addr->SetIp(ip.GetValue());
addr->SetPort(port);
bool connected = Socket->Connect(*addr);
if (connected){
UE_LOG(LogTemp, Warning, TEXT("Socket connection successful"));
TArray<uint8> ReceivedData;
uint32 Size;
while (Socket->HasPendingData(Size))
{
ReceivedData.Init(FMath::Min(Size, 65507u));
int32 Read = 0;
Socket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data Read! %d"), ReceivedData.Num()));
}
return true;
}
else{
UE_LOG(LogTemp, Warning, TEXT("Cannot create socket connection"));
return false;
}
Socket->Close();
}
I can’t help myself…