日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

libevent evhttp学习——http服务端

發布時間:2025/3/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 libevent evhttp学习——http服务端 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

http服務端相對客戶端要簡單很多,我們仍舊使用libevent-2.1.5版本,服務端接口和2.0版本沒有區別

基本流程

http服務端使用到的借口函數及流程如下

  • 創建event_base和evhttp

    struct event_base *event_base_new(void); struct evhttp *evhttp_new(struct event_base *base);
    • 1
    • 2
  • 綁定地址和端口

    int evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port);
    • 1
  • 設置處理函數

    void evhttp_set_gencb(struct evhttp *http,void (*cb)(struct evhttp_request *, void *), void *arg);
    • 1
    • 2
  • 派發事件循環

    int event_base_dispatch(struct event_base *);
    • 1
  • 完整代碼

    服務器接收到請求后打印URL,并返回一段文本信息

    #include "event2/http.h" #include "event2/event.h" #include "event2/buffer.h"#include <stdlib.h> #include <stdio.h>void HttpGenericCallback(struct evhttp_request* request, void* arg) {const struct evhttp_uri* evhttp_uri = evhttp_request_get_evhttp_uri(request);char url[8192];evhttp_uri_join(const_cast<struct evhttp_uri*>(evhttp_uri), url, 8192);printf("accept request url:%s\n", url);struct evbuffer* evbuf = evbuffer_new();if (!evbuf){printf("create evbuffer failed!\n");return ;}evbuffer_add_printf(evbuf, "Server response. Your request url is %s", url);evhttp_send_reply(request, HTTP_OK, "OK", evbuf);evbuffer_free(evbuf); }int main(int argc, char** argv) {if (argc != 2){printf("usage:%s port\n", argv[0]);return 1;}int port = atoi(argv[1]);if (port == 0){printf("port error:%s\n", argv[1]);return 1;}struct event_base* base = event_base_new();if (!base){printf("create event_base failed!\n");return 1;}struct evhttp* http = evhttp_new(base);if (!http){printf("create evhttp failed!\n");return 1;}if (evhttp_bind_socket(http, "0.0.0.0", port) != 0){printf("bind socket failed! port:%d\n", port);return 1;}evhttp_set_gencb(http, HttpGenericCallback, NULL);event_base_dispatch(base);return 0; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    編譯

    g++ http-server.cpp -I/opt/third_party/libevent/include -L/opt/third_party/libevent/lib -levent -o http-server

    總結

    以上是生活随笔為你收集整理的libevent evhttp学习——http服务端的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。