【问题标题】:How can I make http request on C++ without blocking the UI thread如何在 C++ 上发出 http 请求而不阻塞 UI 线程
【发布时间】:2017-06-14 02:26:32
【问题描述】:

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

【问题讨论】:

    标签: android c++ ios android-ndk


    【解决方案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));
    }
    }
    

    【讨论】:

    • 谢谢,真的是纯libcurl,我喜欢:)
    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多