【问题标题】:Why does evhttp_request_get_connection() always return NULL?为什么 evhttp_request_get_connection() 总是返回 NULL?
【发布时间】:2013-07-22 10:17:40
【问题描述】:

在以下示例程序中:

#include <event2/event.h>
#include <event2/http.h>
#include <assert.h>

void response_cb(struct evhttp_request* req, void *arg) {
    assert(evhttp_request_get_response_code(req)<400);/* passes */
    assert(evhttp_request_get_connection(req));/* FAILS ??? */
}

int main(int argc, char **argv) {
    struct event_base* ev_base;
    struct evhttp_connection *http_conn;
    struct evhttp_request *req;

    ev_base = event_base_new();
    http_conn = evhttp_connection_base_new(ev_base, NULL, "google.com", 80);
    req = evhttp_request_new(response_cb, NULL);

    evhttp_make_request(http_conn, req, EVHTTP_REQ_GET, "/");

    event_base_dispatch(ev_base);
    return -1;
}

在 response_cb 中,第一个断言按预期通过,但秒失败,即 evhttp_request_get_connection(req) 返回 NULL。这是为什么呢?

evhttp_request_get_connection 声明的文档:

返回与请求关联的连接对象或NULL。

但我仍然有联系。我不会随处丢弃它。

我做错了什么还是这是一个错误或只是一些晦涩的功能?

【问题讨论】:

    标签: http null connection request libevent


    【解决方案1】:

    您无法在响应回调中获得指向该连接的指针,因为该连接已被释放(关闭,或在启用 HTTP keepalive 时保持打开以供重用)。

    您可以在 evhttp_connection_done()(http.c,大约第 780 到 817 行)中看到,在请求的连接字段 (evcon) 设置为 NULL 后调用响应回调。不过,我确实同意 evhttp API 不是很清楚。

    【讨论】:

    • keep-alive 似乎与此问题无关。根据 http.c : evhttp_connection_done() req->evcon = NULL 为所有传出连接设置,不仅为非保持活动连接。
    • 嗯,这只是一个例子,而不是对可能重用连接的所有情况进行彻底检查。对不起,如果看起来是这样。
    猜你喜欢
    • 2014-09-12
    • 2019-09-18
    • 2014-09-02
    • 2015-02-27
    • 2021-01-10
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多