如何在不阻塞UI线程的情况下在C ++上发出http请求

时间:2017-06-14 02:26:32

标签: android c++ ios android-ndk

我目前正在开发使用oxygine / sdl / coco2d的手机游戏。 但正常的http请求似乎阻止了渲染更新(挂起)以获得响应,我已经尝试了很多c ++请求库但却找不到。 是否有任何http客户端可以在不阻止UI线程的情况下应用于移动http请求。

1 个答案:

答案 0 :(得分:1)

您可以使用backcurl>> https://github.com/Taymindis/backcurl,它纯粹依赖于基于libcurl。您可以使用bcl::setOpts(.... )自定义请求,它适用于非阻止UI请求。

示例代码

// Derived from example/main.cpp
void doGuiWork() {
    printf("\r %s --- %d", "Drawing thousand Pieces of Color with count elapsed ", countUI++);
}


void doUpdate() {
bcl::LoopBackFire();
}

void doRunOnUI () {
bool gui_running = true;
std::cout << "Game is running thread: ";
 bcl::executeOnUI<std::string>([](bcl::Request * req) -> void {
    bcl::setOpts(req, CURLOPT_URL , "http://www.google.com",
    CURLOPT_FOLLOWLOCATION, 1L,
    CURLOPT_WRITEFUNCTION, &bcl::writeContentCallback,
    CURLOPT_WRITEDATA, req->dataPtr,
    CURLOPT_USERAGENT, "libcurl-agent/1.0",
    CURLOPT_RANGE, "0-200000"
                );
}, [&](bcl::Response * resp) {
    printf("On UI === %s\n", resp->getBody<std::string>()->c_str());
    printf("Done , stop gui running with count ui %d\n", countUI );
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    gui_running = false;
});

while (gui_running) {
    doGuiWork();
    doUpdate();
    std::this_thread::sleep_for(std::chrono::milliseconds(1000 / 16));
}
}