【发布时间】: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