- #include "MatchmakingJob.h"
- #include "Sockets.h"
- #include "Interfaces/IPv4/IPv4Endpoint.h"
- #pragma optimize("", off)
- MatchmakingJob::MatchmakingJob(FString& stateToWriteInto)
- : currentState(stateToWriteInto)
- {}
- bool MatchmakingJob::Init()
- {
- const FIPv4Endpoint RemoteAddressForConnection = FIPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1336);
- ConnectionSocket = ISocketSubsystem::Get()->CreateSocket("Stream", "MatchmakingServer");
- if(!ConnectionSocket)
- {
- return false;
- }
- const TSharedRef<FInternetAddr> Address = ISocketSubsystem::Get()->CreateInternetAddr(RemoteAddressForConnection.Address.Value, RemoteAddressForConnection.Port);
- return ConnectionSocket->Connect(Address.Get());
- }
- uint32 MatchmakingJob::Run()
- {
-
- currentState = "Connected To matchmaking Server!";
-
- SleepThread();
- #pragma region SendRequest
-
-
-
-
- FString Serialized = FString::FromInt(CLIENT_MESSAGE_REQUESTCONNECTION);
- const TCHAR* serializedChar = Serialized.GetCharArray().GetData();
- int32 Size = FCString::Strlen(serializedChar);
- int32 Sent = 0;
-
- if(!ConnectionSocket->Send(reinterpret_cast<uint8*>(TCHAR_TO_UTF8(serializedChar)), Size, Sent))
- {
-
- JobCompletedEvent.Broadcast(false, "");
- return 1;
- }
-
- currentState = "Request Sent! Waiting For Server To Find Match";
- SleepThread();
- #pragma endregion
- #pragma region ReceiveReply
-
- uint8 ReceiveBuffer[128];
- FMemory::Memset(ReceiveBuffer, 0, sizeof(uint8) * 128);
- int32 BytesRead = 0;
- FString FullMessage = "";
-
-
- if(!ConnectionSocket->Recv(ReceiveBuffer, 128, BytesRead))
- {
-
- JobCompletedEvent.Broadcast(false, "");
- return 2;
- }
-
- FullMessage.Append(reinterpret_cast<const char*>(ReceiveBuffer));
-
- currentState = "Ready To Connect To Server!: " + FullMessage;
- FPlatformProcess::Sleep(1.0f);
- #pragma endregion
- #pragma region SendConfirmation
-
-
- Serialized = TEXT( "" + FString::FromInt(CLIENT_MESSAGE_CONFIRMDONE) );
- serializedChar = Serialized.GetCharArray().GetData();
- Size = FCString::Strlen(serializedChar);
- Sent = 0;
-
- if(!ConnectionSocket->Send(reinterpret_cast<uint8*>(TCHAR_TO_UTF8(serializedChar)), Size, Sent))
- {
-
- JobCompletedEvent.Broadcast(false, "");
- return 3;
- }
- #pragma endregion
-
- JobCompletedEvent.Broadcast(true, FullMessage);
- return 0;
- }
- void MatchmakingJob::Exit()
- {
- FRunnable::Exit();
- }
- void MatchmakingJob::Stop()
- {
- FRunnable::Stop();
- }
- void MatchmakingJob::SleepThread()
- {
- #if !UE_BUILD_SHIPPING
- FPlatformProcess::Sleep(1.0f);
- #endif
- }
- #pragma optimize("", on)