0

我已经建立了一个使用 PHP 脚本和 MySQL 数据库运行的多人专用服务器。我正在尝试通过 HTTP 访问服务器以发送/接收游戏数据,从获取服务器状态这样简单的事情开始。

我已经能够使用 Unreal Doc 的 IHttpRequest 成功联系服务器:

void ANetwork::getContentsOfURL(FString URL)
{
    serverResponse = NULL;

    TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
    HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
    HttpRequest->SetURL(URL);
    HttpRequest->SetVerb(TEXT("POST"));

    //Creating JSON Object
    FString json = "{\"auth\":\"" + authenticator = "\"";

    json += "}";

    HttpRequest->SetContentAsString(json);
    HttpRequest->OnProcessRequestComplete().BindUObject(this, &ANetwork::OnResponseReceived);
    HttpRequest->ProcessRequest();
}

void ANetwork::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
    GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, Response->GetContentAsString());

    if (!Response.IsValid())
    {
        serverResponse = "FAIL";
    }
    else
    {
        serverResponse = Response->GetContentAsString();
    }
}

这将正确的代码与调试器相呼应,所以我知道服务器正在工作并且代码实际上正在获取它需要获取的内容。但是,我需要能够以 FString 的形式获取 HTTP 响应并将其返回给调用者,以便我可以在游戏中使用它。现在这个方法是异步的,这会阻止我返回响应。

如何进行同步 HTTP 请求,以便可以将响应作为字符串返回给调用者?

IE

FString ANetwork::getContentsOfURL(FString URL)
4

1 回答 1

1

Reset (unsignal) an event at the bottom of getContentsOfUrl. Await for it to become signaled. Signal the event from OnResponseReceived.

CreateEvent https://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx ResetEvent https://msdn.microsoft.com/en-us/library/windows/desktop/ms685081(v=vs.85).aspx WaitForSingleObject https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx SetEvent (signals it) https://msdn.microsoft.com/en-us/library/windows/desktop/ms686211(v=vs.85).aspx

HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

// bottom getCongentsOfUrl:
ResetEvent(hEvent); // optional because inital state is unsignaled
WaitForSingleObject(hEvent);

// OnResponseReceived
SetEvent(hEvent)
于 2015-04-11T18:25:28.743 回答