2013-09-11

Libevent 2 HTTP 客户端示例

Views: 20953 | Add Comments

Libevent 的文档非常少, 而且示例也很奇缺, 在 Google 里一搜, 还真找不到一两个. 这里贴一个最简单的利用 Libevent 2 HTTP 库, 作为客户端向服务器发起请求的例子.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <evhttp.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/bufferevent.h>

void http_request_done(struct evhttp_request *req, void *arg){
    char buf[1024];
    int s = evbuffer_remove(req->input_buffer, &buf, sizeof(buf) - 1);
    buf[s] = '\0';
    printf("%s", buf);
    // terminate event_base_dispatch()
    event_base_loopbreak((struct event_base *)arg);
}

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

    base = event_base_new();
    conn = evhttp_connection_base_new(base, NULL, "127.0.0.1", 8080);
    req = evhttp_request_new(http_request_done, base);

    evhttp_add_header(req->output_headers, "Host", "localhost");
    //evhttp_add_header(req->output_headers, "Connection", "close");

    evhttp_make_request(conn, req, EVHTTP_REQ_GET, "/index.php?id=1");
    evhttp_connection_set_timeout(req->evcon, 600);
    event_base_dispatch(base);

    return 0;
}

Related posts:

  1. 150行C代码的comet服务器
  2. Libevent HTTP 内存泄露
  3. 让libevent HTTP服务器立即知道客户端的断开
  4. 基于列的数据库
  5. 使用 jemalloc 编译过程出错的问题
Posted by ideawu at 2013-09-11 21:53:02 Tags:

Leave a Comment