c++ 稳定web服务器开发

2021/5/7 20:28:20

本文主要是介绍c++ 稳定web服务器开发,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

采用libevhtp库

 

libevhtp-1.2.15官网下载

 

 

 

wget "https://github.com/ellzey/libevhtp/archive/1.2.15.tar.gz" -O libevhtp-1.2.15.tar.gz

yum install libevent.x86_64 libevent-devel.x86_64

 yum install openssl openssl-devel

yum install cmake

进到程序的build 后cmake ..

 

 

 


#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.121.47", 8081, 1024);
    event_base_loop(evbase, 0);
    
    return 0;
}

 

 

运行的堆栈是这样

 

编译脚本

 g++ -o httpserver httpserver.cpp -I/home/tool/libevhtp-1.2.15/include/ -L/home/tool/libevhtp-1.2.15/build/ -levhtp -levent -lpthread -levent_openssl -lssl -lcrypto

 

    event_base_loop(m_evBase, EVLOOP_ONCE|EVLOOP_NONBLOCK);

 

这里可以修改成异步的接口

 

 

 

 


 

 



这篇关于c++ 稳定web服务器开发的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程