#include <event2/event.h> #include <event2/listener.h> #include <string.h> #include <iostream> #include <signal.h> #define SPORT 5001 using namespace std; void listen_cb(struct evconnlistener * e, evutil_socket_t s, struct sockaddr *a, int socklen, void *arg) { cout << "listen_cb. "; } int main() { //忽略管道破裂信号,发送数据给已关闭的socket, if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) return 1; cout << "test server. "; event_base * base = event_base_new(); if (base) { cout << "event_base_new success. "; } //监听端口 //socket创建,bind,listen,绑定连接事件 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, //连接队列长度 (sockaddr*)&sin, //绑定的地址和端口 sizeof(sin) ); //事件分发处理 if (base) event_base_dispatch(base); //清理 if (ev) evconnlistener_free(ev); if (base) event_base_free(base); return 0; }