ubuntu c++ http服务端event使用

2024-08-30 14:28

本文主要是介绍ubuntu c++ http服务端event使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

程序:

#ifndef PLATFROMCOMMUNICATION_H
#define PLATFROMCOMMUNICATION_H#include <iostream>
#include <fstream>
#include <unistd.h>
#include <curl/curl.h>#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <string.h>#include <event.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <event2/http_compat.h>
#include <event2/util.h>#include <jsoncpp/json/json.h>#define ETH_NAME "ens33"
#define MYHTTPD_SIGNATURE   "MoCarHttpd v0.1"using namespace std;class RouteTasks{
public:RouteTasks();void init();private:static void login(struct evhttp_request *req, void *arg);string getIp();int m_port;int m_timeout;
};#endif // PLATFROMCOMMUNICATION_H
#include "platfromcommunication.h"RouteTasks::RouteTasks()
{m_port = 9000;m_timeout = 120;
}void RouteTasks::init()
{//服务端//初始化event APIevent_init();//创建一个http serverstruct evhttp *httpd;httpd = evhttp_start(getIp().c_str(), m_port);evhttp_set_timeout(httpd, m_timeout);//也可以为特定的URI指定callbackevhttp_set_cb(httpd, "/cgi-bin/entry.cgi/system/login", &RouteTasks::login, NULL);//循环处理eventsevent_dispatch();evhttp_free(httpd);
}void RouteTasks::login(evhttp_request *req, void *arg)
{char request_data[4096] = {0};//获取POST方法的数据size_t post_size = EVBUFFER_LENGTH(req->input_buffer);char *post_data = (char *) EVBUFFER_DATA(req->input_buffer);memcpy(request_data, post_data, post_size);printf("got control_device_start_stop connection post_data = %s, len =%ld\n", post_data, post_size);//解析获得的数据string deviceCode;string ptz;Json::Value jvalue;Json::Reader jreader;jreader.parse(request_data, jvalue);deviceCode = jvalue["sUserName"].asString();ptz = jvalue["sPassword"].asString();cout<<"============================\n"<<"deviceCode: "<<deviceCode<<" ptz: "<<ptz<<"\n-------------------------\n"<<endl;//给前段回复一个响应结果Json::Value root;Json::FastWriter fastWriter;root["code"] = Json::Value("200");root["msg"] = Json::Value("成功");cout<<"return post"<<fastWriter.write(root)<<endl;/* 输出到客户端 *///HTTP headerevhttp_add_header(req->output_headers, "Server", MYHTTPD_SIGNATURE);evhttp_add_header(req->output_headers, "Content-Type", "application/json; charset=UTF-8");evhttp_add_header(req->output_headers, "Connection", "close");//输出的内容struct evbuffer *buf;buf = evbuffer_new();evbuffer_add_printf(buf, "%s", fastWriter.write(root).c_str());//将封装好的evbuffer 发送给客户端evhttp_send_reply(req, HTTP_OK, "OK", buf);evbuffer_free(buf);
}string RouteTasks::getIp()
{struct sockaddr_in sin;struct ifreq ifr;int sockfd = socket(AF_INET, SOCK_DGRAM, 0);if(sockfd == -1) {perror("socket error");return "";}strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);if(ioctl(sockfd, SIOCGIFADDR, &ifr) == 0) {memcpy(&sin, &ifr.ifr_addr, sizeof (ifr.ifr_addr));cout<<ETH_NAME<<" ip : "<<inet_ntoa(sin.sin_addr)<<endl;return inet_ntoa(sin.sin_addr);}return "";
}
#include <iostream>
#include "platfromcommunication.h"using namespace std;//当向进程发出SIGTERM/SIGHUP/SIGINT/SIGQUIT的时候,终止event的事件侦听循环
void signal_handler(int sig) {switch (sig) {case SIGTERM:case SIGHUP:case SIGQUIT:case SIGINT:event_loopbreak();  //终止侦听event_dispatch()的事件侦听循环,执行之后的代码break;}
}int main()
{cout<<"hello world"<<endl;signal(SIGHUP, signal_handler);signal(SIGTERM, signal_handler);signal(SIGINT, signal_handler);signal(SIGQUIT, signal_handler);RouteTasks rt;rt.init();while (1) {sleep(1);}return 0;
}

编译: -levent

由于在ubuntu中https服务端event是阻塞式运行的,所以在正式项目中,可以将其放入线程中,这样不会阻塞程序运行,具体方式如下:上程序

#ifndef PLATFROMCOMMUNICATION_H
#define PLATFROMCOMMUNICATION_H#include <iostream>
#include <fstream>
#include <unistd.h>
#include <curl/curl.h>#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <string.h>#include <event.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <event2/http_compat.h>
#include <event2/util.h>#include <jsoncpp/json/json.h>
#include <boost/thread.hpp>#define ETH_NAME "ens33"
#define MYHTTPD_SIGNATURE   "MoCarHttpd v0.1"using namespace std;class RouteTasks{
public:RouteTasks();~RouteTasks();void init();private:static void login(struct evhttp_request *req, void *arg);static void init_thread(void *arg);void init_sub();string getIp();int m_port;int m_timeout;//创建一个http serverstruct evhttp *httpd;
};#endif // PLATFROMCOMMUNICATION_H
#include "platfromcommunication.h"RouteTasks::RouteTasks()
{m_port = 7777;m_timeout = 120;//初始化event APIevent_init();
}RouteTasks::~RouteTasks()
{evhttp_free(httpd);
}void RouteTasks::init()
{boost::thread t(&RouteTasks::init_thread, this);
}void RouteTasks::login(evhttp_request *req, void *arg)
{char request_data[4096] = {0};//获取POST方法的数据size_t post_size = EVBUFFER_LENGTH(req->input_buffer);char *post_data = (char *) EVBUFFER_DATA(req->input_buffer);memcpy(request_data, post_data, post_size);printf("got control_device_start_stop connection post_data = %s, len =%ld\n", post_data, post_size);//解析获得的数据string deviceCode;string ptz;Json::Value jvalue;Json::Reader jreader;jreader.parse(request_data, jvalue);deviceCode = jvalue["sUserName"].asString();ptz = jvalue["sPassword"].asString();cout<<"============================\n"<<"deviceCode: "<<deviceCode<<" ptz: "<<ptz<<"\n-------------------------\n"<<endl;//给前段回复一个响应结果Json::Value root;Json::FastWriter fastWriter;root["code"] = Json::Value("200");root["msg"] = Json::Value("成功");cout<<"return post"<<fastWriter.write(root)<<endl;/* 输出到客户端 *///HTTP headerevhttp_add_header(req->output_headers, "Server", MYHTTPD_SIGNATURE);evhttp_add_header(req->output_headers, "Content-Type", "application/json; charset=UTF-8");evhttp_add_header(req->output_headers, "Connection", "close");//输出的内容struct evbuffer *buf;buf = evbuffer_new();evbuffer_add_printf(buf, "%s", fastWriter.write(root).c_str());//将封装好的evbuffer 发送给客户端evhttp_send_reply(req, HTTP_OK, "OK", buf);evbuffer_free(buf);
}void RouteTasks::init_thread(void *arg)
{RouteTasks* rt = (RouteTasks*)arg;rt->init_sub();
}void RouteTasks::init_sub()
{//服务端
//    //初始化event API
//    event_init();//    //创建一个http server
//    struct evhttp *httpd;httpd = evhttp_start(getIp().c_str(), m_port);evhttp_set_timeout(httpd, m_timeout);//也可以为特定的URI指定callbackevhttp_set_cb(httpd, "/cgi-bin/entry.cgi/system/login", &RouteTasks::login, NULL);//循环处理eventsevent_dispatch();//    evhttp_free(httpd);
}string RouteTasks::getIp()
{struct sockaddr_in sin;struct ifreq ifr;int sockfd = socket(AF_INET, SOCK_DGRAM, 0);if(sockfd == -1) {perror("socket error");return "";}strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);if(ioctl(sockfd, SIOCGIFADDR, &ifr) == 0) {memcpy(&sin, &ifr.ifr_addr, sizeof (ifr.ifr_addr));cout<<ETH_NAME<<" ip : "<<inet_ntoa(sin.sin_addr)<<endl;return inet_ntoa(sin.sin_addr);}return "";
}
#include <iostream>
#include "platfromcommunication.h"using namespace std;//当向进程发出SIGTERM/SIGHUP/SIGINT/SIGQUIT的时候,终止event的事件侦听循环
void signal_handler(int sig) {switch (sig) {case SIGTERM:case SIGHUP:case SIGQUIT:case SIGINT:event_loopbreak();  //终止侦听event_dispatch()的事件侦听循环,执行之后的代码break;}
}int main()
{cout<<"hello world"<<endl;signal(SIGHUP, signal_handler);signal(SIGTERM, signal_handler);signal(SIGINT, signal_handler);signal(SIGQUIT, signal_handler);RouteTasks rt;rt.init();while (1) {sleep(1);}return 0;
}

这篇关于ubuntu c++ http服务端event使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1121074

相关文章

springboot security使用jwt认证方式

《springbootsecurity使用jwt认证方式》:本文主要介绍springbootsecurity使用jwt认证方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录前言代码示例依赖定义mapper定义用户信息的实体beansecurity相关的类提供登录接口测试提供一

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.

java中使用POI生成Excel并导出过程

《java中使用POI生成Excel并导出过程》:本文主要介绍java中使用POI生成Excel并导出过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求说明及实现方式需求完成通用代码版本1版本2结果展示type参数为atype参数为b总结注:本文章中代码均为

Spring Boot3虚拟线程的使用步骤详解

《SpringBoot3虚拟线程的使用步骤详解》虚拟线程是Java19中引入的一个新特性,旨在通过简化线程管理来提升应用程序的并发性能,:本文主要介绍SpringBoot3虚拟线程的使用步骤,... 目录问题根源分析解决方案验证验证实验实验1:未启用keep-alive实验2:启用keep-alive扩展建

新特性抢先看! Ubuntu 25.04 Beta 发布:Linux 6.14 内核

《新特性抢先看!Ubuntu25.04Beta发布:Linux6.14内核》Canonical公司近日发布了Ubuntu25.04Beta版,这一版本被赋予了一个活泼的代号——“Plu... Canonical 昨日(3 月 27 日)放出了 Beta 版 Ubuntu 25.04 系统镜像,代号“Pluc

使用Java实现通用树形结构构建工具类

《使用Java实现通用树形结构构建工具类》这篇文章主要为大家详细介绍了如何使用Java实现通用树形结构构建工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录完整代码一、设计思想与核心功能二、核心实现原理1. 数据结构准备阶段2. 循环依赖检测算法3. 树形结构构建4. 搜索子

GORM中Model和Table的区别及使用

《GORM中Model和Table的区别及使用》Model和Table是两种与数据库表交互的核心方法,但它们的用途和行为存在著差异,本文主要介绍了GORM中Model和Table的区别及使用,具有一... 目录1. Model 的作用与特点1.1 核心用途1.2 行为特点1.3 示例China编程代码2. Tab

SpringBoot使用OkHttp完成高效网络请求详解

《SpringBoot使用OkHttp完成高效网络请求详解》OkHttp是一个高效的HTTP客户端,支持同步和异步请求,且具备自动处理cookie、缓存和连接池等高级功能,下面我们来看看SpringB... 目录一、OkHttp 简介二、在 Spring Boot 中集成 OkHttp三、封装 OkHttp