【问题标题】:libevent multithreaded http server: can't reply evhttp_request successfully in sub threadslibevent多线程http服务器:无法在子线程中成功回复evhttp_request
【发布时间】:2019-02-15 12:29:38
【问题描述】:

问题是:客户端无法在服务器端的子线程中接收以“evhttp_send_reply”回复的http响应。

我已经尝试使用 libevent evhttp 设置多线程 http 服务器的模型,下面的代码在主线程中运行:

    struct event_base *mpEventBase = event_base_new();
    struct evhttp *pHttp = evhttp_new(mpEventBase);
    evhttp_bind_socket(pHttp, "0.0.0.0", port);
    evhttp_set_gencb(pHttp, HttpGenericCallback, (void *)this);
    event_base_dispatch(mpEventBase);

然后http服务器设置并开始接受来自客户端的连接。 但是对于处理长时间运行代码的一般情况,我将所有http请求转发到子线程并在子线程中发送http响应。

    void HttpGenericCallback(struct evhttp_request *pRequest, void* arg) {
        Class *thiz = (Class *)arg;
        // run in sub thread in thread pool
        thiz->mpThreadPool->Run([thiz](struct evhttp_request *pReq){
            struct evbuffer* pEvbuf = evbuffer_new();
            if (!pEvbuf) {
                std::cout << "create evbuffer failed!\n";
                return ;
            }

            const char *pUrl = evhttp_request_get_uri(pRequest);
            evbuffer_add_printf(pEvbuf, "Server response. Your request url is %s", pUrl);
            evhttp_send_reply(pRequest, HTTP_OK, "OK", pEvbuf);
            evbuffer_free(pEvbuf);
        }, pRequest);
    }

但是,我发现在“evhttp_send_reply”之后,客户端没有收到任何响应。我不确定哪一步是错误的? 另外,如果我将子线程中运行的代码移动到HttpGenericCallback,它会起作用!

非常感谢任何建议!

【问题讨论】:

    标签: libevent


    【解决方案1】:

    您的HttpGenericCallback 被调用并且您将struct evhttp_request* 传递给您的线程。 HttpGenericCallback 完成并可能破坏您的 struct evhttp_request*,而您的线程继续使用已经无效的指针。

    编辑:我了解到 evhttp_request 直到 evhttp_send_reply 之后才被删除。不过,我想提一下,线程使用 pRequest 但应该使用 pReq,即传递给函数的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-11
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2011-08-06
      相关资源
      最近更新 更多