使用libevhtp编写接收客户端输入参数的HTTP服务器

本文主要介绍使用 libevhtp 编写一个HTTP服务器,该服务器可以接收HTTP客户端发送的 GET/POST 请求,并获取相应的请求参数。

1 示例程序及测试

示例代码(libevhtptest1.cpp)如下:

#include "evhtp/evhtp.h"
#include <iostream>

using namespace std;

void testcb(evhtp_request_t* req, void* a)
{
    cout << "HTTP client request info as followed: " << endl;
    
    // 获取HTTP客户端的请求方式
    htp_method eRequestMethod = evhtp_request_get_method(req);

    // 根据不同的HTTP客户端请求方式,获取请求数据
    // HTTP客户端请求方式为GET
    if (htp_method_GET == eRequestMethod)
    {
        cout << "GET method!" << endl;
        cout << "GET data(uri) is: " << req->uri->query_raw << endl;
        unsigned char* RequestData = req->uri->query_raw;
        cout << "GET data(content) is: " << RequestData << endl;
    }
    // HTTP客户端请求方式为POST
    else if (htp_method_POST == eRequestMethod)
    {
        cout << "POST method!" << endl;
        char RequestData[1024] = {'\0'};
        evbuffer_copyout(req->buffer_in, RequestData, evhtp_request_content_len(req));
        cout << "POST data(content) is: " << RequestData << endl;
    }
    
    evbuffer_add_reference(req->buffer_out, "This is a HTTP server response.\n", 32, NULL, NULL);
    evhtp_send_reply(req, EVHTP_RES_OK);
}

int main(int argc, char ** argv)
{
    evbase_t* evbase = event_base_new();
    evhtp_t* htp = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/evhtptest1/", testcb, NULL);
    evhtp_bind_socket(htp, "192.168.213.128", 8081, 1024);
    event_base_loop(evbase, 0);
    
    return 0;
}

编译上述代码,如下:

g++ -o libevhtptest1 libevhtptest1.cpp -I/usr/local/include/ -levhtp -levent -lpthread -levent_openssl -lssl -lcrypto

运行编译生成的 HTTP 服务器(libevhtptest1),如下:

[root@node1 /opt/liitdar/mydemos/simples]# ./libevhtptest1 
 

确认 HTTP 服务器是否已经监听8081端口、等待HTTP客户端的连接,如下:

[root@node1 ~]# netstat -anpot|grep 8081
tcp        0      0 192.168.213.128:8081    0.0.0.0:*               LISTEN      3409/./libevhtptest  off (0.00/0/0)
[root@node1 ~]# 

上述查询结果显示 HTTP 服务器(libevhtptest1)已经在等待HTTP客户端的连接了。我们使用 curl 命令发送 GET/POST 请求,测试编写的 HTTP 服务器功能是否正常,测试过程及结果如下:

1. 发送 GET 请求

HTTP客户端信息如下:

[root@node1 ~]# curl http://192.168.213.128:8081/evhtptest1/?requesttype=GET
This is a HTTP server response.
[root@node1 ~]# 

HTTP服务端信息如下:

[root@node1 /opt/liitdar/mydemos/simples]# ./libevhtptest1 
HTTP client request info as followed: 
GET method!
GET data(uri) is: requesttype=GET
GET data(content) is: requesttype=GET

2. 发送 POST 请求

HTTP客户端信息如下:

[root@node1 ~]# curl -d 'requesttype=POST' http://192.168.213.128:8081/evhtptest1/
This is a HTTP server response.
[root@node1 ~]# 

HTTP服务端信息如下:

HTTP client request info as followed: 
POST method!
POST data(content) is: requesttype=POST

通过上述测试能够看到,我们编写的HTTP 服务器(libevhtptest1)能够正常地接收HTTP客户端发送的 GET/POST 请求,并获取相应的请求参数。

猜你喜欢

转载自blog.csdn.net/liitdar/article/details/81325512