From 599af79f8b578c2785db7c0d81af23e4400a49e2 Mon Sep 17 00:00:00 2001 From: panyufeng <3043130461@qq.com> Date: Tue, 8 Jun 2021 23:48:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4libevent=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E9=85=8D=E7=BD=AEcode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test_conf/test_conf.cpp | 60 +++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/test_conf/test_conf.cpp b/test_conf/test_conf.cpp index aa151a6..d89d43e 100644 --- a/test_conf/test_conf.cpp +++ b/test_conf/test_conf.cpp @@ -1,13 +1,22 @@  #include #include - -#ifndef _WIN32 -#include +#include +#include +#ifdef _WIN32 + +#else + #include #endif // !_WIN32 using namespace std; +#define SPORT 5001 + +void listen_cb(struct evconnlistener *, evutil_socket_t, struct sockaddr *, int socklen, void *arg) { + std::cout << "listen to be" << std::endl; +} + int main() { #ifdef _WIN32 @@ -23,16 +32,32 @@ int main() //初始化libevent上下文 event_config *conf = event_config_new(); - //显示支持的网络模式 + //打印支持的网络模式 const char** methods = event_get_supported_methods(); cout << "supported_methods" << endl; for (int i = 0; methods[i] != NULL; i++) { cout << methods[i] << endl; } - //设置特征 - //event_config_require_features(conf, EV_FEATURE_FDS); + //设置了EV_FEATURE_FDS 其它特征就无法设置,在windows中EV_FEATURE_FDS无效 + //event_config_require_features(conf, EV_FEATURE_FDS); //不支持epoll + + //设置网络模型使用select + //event_config_avoid_method(conf, "epoll"); //linux 默认顺序为 epoll -> poll -> select + //event_config_avoid_method(conf, "poll"); + + + //windows中支持IOCP(线程池) 要查看该项是否开启成功,可以在运行程序后打开任务管理器查看线程数量 +#ifdef _WIN32 + event_config_set_flag(conf, EVENT_BASE_FLAG_STARTUP_IOCP); + evthread_use_windows_threads(); + //设置cpu数量 + SYSTEM_INFO si; + GetSystemInfo(&si); + event_config_set_num_cpus_hint(conf, si.dwNumberOfProcessors); +#endif + //初始化配置上下文 event_base* base = event_base_new_with_config(conf); @@ -45,7 +70,6 @@ int main() cerr << "event_base_new failed" << endl; return 0; } - } else { //获取当前网络模型 @@ -79,14 +103,28 @@ int main() cout << "EV_FEATURE_EARLY_CLOSE events are not supported" << endl; } - - cout << "event_base_new_with_config success!" << endl; - event_config_free(conf); - } + sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); + sin.sin_family = AF_INET; + sin.sin_port = htons(SPORT); + + evconnlistener * ev = evconnlistener_new_bind(base, //libevent上下文 + listen_cb, //接收到连接的回调函数 + base, //回调函数获取的参数(根据业务来) + LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, //地址重用,evconnlistener关闭同时关闭socket + 10, //连接队列大小,对应listen函数参数 + (sockaddr*)&sin,//绑定的地址和端口 + sizeof(sin) + ); + event_base_dispatch(base); + event_base_free(base); + evconnlistener_free(ev); + event_config_free(conf); + } return 0; }