基于libevent实现http服务端和客户端

c++基于libevent库实现的客户端和服务端(GET和POST)

头文件:http_event.hpp

#ifndef __HTTP_EVENT_HPP__
#define __HTTP_EVENT_HPP__

#include <iostream>
#include <sstream>

#include "evhttp.h"
#include "event.h"

using namespace std;

// ev http server
class evHttpServer
{
private:
    string ip;
    int port;
    struct evhttp *http_server = NULL;
    struct event_base *base = NULL;

public:
    evHttpServer(string ip, int port) : ip(ip), port(port){};
    // 创建http 绑ip端口
    bool serverConnect();
    // 设置服务超时时间
    void setHttpTimeout(int timeout);
    /*
        接口注册
        @param path 接口路径 如"/get_task"
        @param cb 处理该接口的回调
        @param cb_arg 回调的参数
    */
    void interfaceRegister(const char *path,
                           void (*cb)(struct evhttp_request *, void *),
                           void *cb_arg = NULL);
    // 循环监听
    void loopListen();
    ~evHttpServer();

public:
    /*
        http响应
        @param code - 响应码
        @param reason - 响应码对应的说明, 为NULL,使用默认的响应码说明
        @param body - body, 为NULL, 没有body
    */
    static void reply(evhttp_request *request, int code, const char *reason, const char *body);
    // Get回调函数例子
    static void cbGETSample(struct evhttp_request *request, void *arg);
    // 解析request获取GET请求参数
    static char *findGetParam(struct evhttp_request *request, struct evkeyvalq *params, const char *query_char);
    // Post回调函数例子
    static void cbPOSTSample(struct evhttp_request *request, void *arg);
};

// ev http client
class evhttpClient
{
private:
    string ip;
    int port;
    string path = "";
    string body = "";
    int timeout = 10;

public:
    /*
        @param path 资源路径可以包含GET请求参数部分
            如"/getparam?param1=123456&param2=456789"
    */
    evhttpClient(string ip, int port, string path);
    // 直接传入URL进行初始化
    evhttpClient(string url);
    // 添加GET请求参数
    void addGetParam(string name, string value);
    // 设置包体
    void setBody(string body);
    // 返回请求的url
    string getUrl();
    // 设置请求超时时间
    void setTimeout(int timeout);
    /*
        发送GET/POST请求
        @param type http请求类型
        EVHTTP_REQ_GET 1
	    EVHTTP_REQ_POST 2
    */
    bool sendHttpRequest(evhttp_cmd_type type);
    ~evhttpClient();

private:
    // 请求回调函数,可以自行在类外实现
    static void requestCallback(struct evhttp_request *request, void *arg);
};

#endif

源文件:http

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值