// Automatically starts when UE4 is started. // Populates the Token variable with the robot user's token. void CloudyWebAPIImpl::StartupModule() { UE_LOG(CloudyWebAPILog, Warning, TEXT("CloudyWebAPI started")); // Initialize the array with InitialArraySize SaveFileUrls.SetNumUninitialized(InitialArraySize); // BaseUrl will be updated with the correct URL BaseUrl = get_env_var(ENV_VAR_CLOUDYWEB_URL).c_str(); // Token variable will be populated with the robot user's token. AttemptAuthentication(); // Set up socket listener to receive commands from CloudyWeb //Create Socket FIPv4Endpoint Endpoint(SERVER_ENDPOINT); ListenSocket = FTcpSocketBuilder(SERVER_NAME).AsReusable().BoundToEndpoint(Endpoint).Listening(8); //Set Buffer Size int32 NewSize = 0; ListenSocket->SetReceiveBufferSize(BUFFER_SIZE, NewSize); TcpListener = new FTcpListener(*ListenSocket, CONNECTION_THREAD_TIME); TcpListener->OnConnectionAccepted().BindRaw(this, &CloudyWebAPIImpl::InputHandler); FTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateRaw(this, &CloudyWebAPIImpl::CheckConnection), CONNECTION_THREAD_TIME); // initialise class variables InputStr = ""; HasInputStrChanged = false; }
bool FLiveEditorManager::ConnectToRemoteHost( FString IPAddress ) { IPAddress.Replace( TEXT(" "), TEXT("") ); TArray<FString> Parts; IPAddress.ParseIntoArray( Parts, TEXT("."), true ); if ( Parts.Num() != 4 ) return false; uint8 NumericParts[4]; for ( int32 i = 0; i < 4; ++i ) { NumericParts[i] = FCString::Atoi( *Parts[i] ); } FSocket* Socket = FTcpSocketBuilder(TEXT("FLiveEditorManager.RemoteConnection")); FIPv4Endpoint Endpoint(FIPv4Address(NumericParts[0], NumericParts[1], NumericParts[2], NumericParts[3]), LIVEEDITORLISTENSERVER_DEFAULT_PORT); if ( Socket->Connect(*Endpoint.ToInternetAddr()) ) { RemoteConnections.Add(IPAddress, Socket); return true; } else { return false; } }
void ANetworkController::BeginPlay() { // TODO: Move this to a more fitting place FMath::RandInit(FPlatformTime::Cycles()); FMath::SRandInit(FPlatformTime::Cycles()); FIPv4Address Address = FIPv4Address::InternalLoopback; uint32 Port = 5062; TcpServerSocket = FTcpSocketBuilder(TEXT("Controlling TCP Socket")) .AsReusable() .AsNonBlocking() .BoundToAddress(Address) .BoundToPort(Port) .Listening(8) .Build(); int32 NewSize = 0; TcpServerSocket->SetReceiveBufferSize(2 * 1024 * 1024, NewSize); if (!TcpServerSocket) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Listen socket could not be created! ~> %s %d"), *Address.ToText().ToString(), Port)); return; } Listener = new FTcpListener(*TcpServerSocket); Listener->OnConnectionAccepted().BindUObject(this, &ANetworkController::ConnectionAccepted); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, FString::Printf(TEXT("Listening to %s:%d"), *Address.ToText().ToString(), Port)); UWorld* World = GetWorld(); World->GetTimerManager().SetTimer(SendDataTimerHandle, this, &ANetworkController::SendData, 1.0f, true); }
bool UNetworkManager::Start(int32 InPortNum) // Restart the server if configuration changed { if (InPortNum == this->PortNum && this->bIsListening) return true; // Already started if (ConnectionSocket) // Release previous connection { ConnectionSocket->Close(); ConnectionSocket = NULL; } if (TcpListener) // Delete previous configuration first { UE_LOG(LogUnrealCV, Warning, TEXT("Stop previous server")); TcpListener->Stop(); // TODO: test the robustness, will this operation successful? delete TcpListener; } this->PortNum = InPortNum; // Start a new TCPListener FIPv4Address IPAddress = FIPv4Address(0, 0, 0, 0); // int32 PortNum = this->PortNum; // Make this configuable FIPv4Endpoint Endpoint(IPAddress, PortNum); FSocket* ServerSocket = FTcpSocketBuilder(TEXT("FTcpListener server")) // TODO: Need to realease this socket // .AsReusable() .BoundToEndpoint(Endpoint) .Listening(8); if (ServerSocket) { int32 NewSize = 0; ServerSocket->SetReceiveBufferSize(2 * 1024 * 1024, NewSize); } else { this->bIsListening = false; UE_LOG(LogUnrealCV, Warning, TEXT("Cannot start listening on port %d, Port might be in use"), PortNum); return false; } TcpListener = new FTcpListener(*ServerSocket); // TcpListener = new FTcpListener(Endpoint); // This will be released after start // In FSocket, when a FSocket is set as reusable, it means SO_REUSEADDR, not SO_REUSEPORT. see SocketsBSD.cpp TcpListener->OnConnectionAccepted().BindUObject(this, &UNetworkManager::Connected); if (TcpListener->Init()) { this->bIsListening = true; UE_LOG(LogUnrealCV, Warning, TEXT("Start listening on %d"), PortNum); return true; } else { this->bIsListening = false; UE_LOG(LogUnrealCV, Error, TEXT("Can not start listening on port %d"), PortNum); return false; } }
uint32 FTcpMessageTransportConnection::Run() { while (bRun) { // Try sending and receiving messages and detect if they fail or if another connection error is reported. if ((!ReceiveMessages() || !SendMessages() || Socket->GetConnectionState() == SCS_ConnectionError) && bRun) { // Disconnected. Reconnect if requested. if (ConnectionRetryDelay > 0) { UE_LOG(LogTcpMessaging, Verbose, TEXT("Connection to '%s' failed, retrying..."), *RemoteEndpoint.ToString()); FPlatformProcess::Sleep(ConnectionRetryDelay); ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(Socket); Socket = FTcpSocketBuilder(TEXT("FTcpMessageTransport.RemoteConnection")); if (Socket && Socket->Connect(RemoteEndpoint.ToInternetAddr().Get())) { bSentHeader = false; bReceivedHeader = false; UpdateConnectionState(STATE_DisconnectReconnectPending); RemoteNodeId.Invalidate(); } else { if (Socket) { ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(Socket); Socket = nullptr; } bRun = false; } } else { bRun = false; } } FPlatformProcess::Sleep(0.0f); } UpdateConnectionState(STATE_Disconnected); RemoteNodeId.Invalidate(); ClosedTime = FDateTime::UtcNow(); // Clear the delegate to remove a reference to this connection ConnectionStateChangedDelegate.Unbind(); return 0; }
void UMyGameInstance::run() { //Socket = SGI->Socket; //Connection = SGI->Connection; //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "URUCHOMIONO"); if (!dupy) { dupy = 1; FString address = TEXT("0.0.0.0"); int32 port = 65000; bool valid = true; TSharedRef<FInternetAddr> addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr(); //ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->GetLocalHostAddr; addr->SetIp(*address, valid); addr->SetPort(port); //addr->GetIp(addresssss); FIPv4Endpoint Endpoint(addr); Socket = FTcpSocketBuilder(TEXT("default")).AsReusable().BoundToEndpoint(Endpoint).Listening(16); //Socket->GetAddress(*adddre); int32 new_size; Socket->SetReceiveBufferSize(2 << 20, new_size); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Connection ~> %d"), Socket != nullptr)); FTimerHandle czaso; GetWorld()->GetTimerManager().ClearTimer(czaso); GetWorld()->GetTimerManager().SetTimer(czaso, this, &UMyGameInstance::TCPConnectionListener, 0.01f, true);//*/ } }
//--------------------------------------------------------------------------------------- // Set remote connection mode. // // #Author(s): Conan Reis void SkUERemote::set_mode(eSkLocale mode) { if (m_mode != mode) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Stop old mode if (m_socket_p) { SkDebug::print(a_str_format("SkookumScript: Disconnecting... %s\n", get_socket_str().as_cstr()), SkLocale_local); ISocketSubsystem * socket_system_p = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM); if (!m_socket_p->Close()) { SkDebug::print(a_str_format(" error closing socket: %i\n", (int32)socket_system_p->GetLastErrorCode()), SkLocale_local); } // Free the memory the OS allocated for this socket socket_system_p->DestroySocket(m_socket_p); m_socket_p = NULL; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Start new mode SkookumRemoteBase::set_mode(mode); // $Revisit - CReis Update debug UI of Skookum IDE connection state switch (mode) { case SkLocale_embedded: set_connect_state(ConnectState_disconnected); SkDebug::print("\nSkookumScript: Skookum IDE not connected (off-line)\n\n", SkLocale_local); break; case SkLocale_runtime: { SkDebug::print("SkookumScript: Attempting to connect to remote IDE\n", SkLocale_local); set_connect_state(ConnectState_connecting); m_socket_p = FTcpSocketBuilder(TEXT("SkookumIDE.RemoteConnection")) .AsReusable() .AsBlocking(); bool success = false; if (m_socket_p) { TSharedPtr<FInternetAddr> ip_addr = get_ip_address_local(); // Check if there's a file named "ide-ip.txt" present in the compiled binary folder // If so, use the ip stored in it to connect to the IDE FString ip_file_path; if (static_cast<SkUERuntime*>(SkUERuntime::ms_singleton_p)->content_file_exists(TEXT("ide-ip.txt"), &ip_file_path)) { ip_file_path /= TEXT("ide-ip.txt"); FString ip_text; if (FFileHelper::LoadFileToString(ip_text, *ip_file_path)) { bool is_valid; ip_addr->SetIp(*ip_text, is_valid); } } ip_addr->SetPort(SkUERemote_ide_port); success = m_socket_p->Connect(*ip_addr); } if (!success) { SkDebug::print("\nSkookumScript: Failed attempt to connect with remote IDE.!\n\n", SkLocale_local); set_mode(SkLocale_embedded); return; } SkDebug::print(a_str_format("SkookumScript: Connected %s\n", get_socket_str().as_cstr()), SkLocale_local); set_connect_state(ConnectState_authenticating); break; } } } }