|
|
#include <iostream>
|
|
#include<event2/event.h>
|
|
#include <event2/listener.h>
|
|
#include <string.h>
|
|
#ifndef _WIN32
|
|
#include <signal.h>
|
|
#endif // !_WIN32
|
|
|
|
|
|
#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
|
|
//初始化socket库
|
|
WSADATA wsa;
|
|
WSAStartup(MAKEWORD(2, 2), &wsa);
|
|
#else
|
|
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { //忽略管道信号,发送数据给已关闭的socket,会飞掉!
|
|
return 1;
|
|
}
|
|
#endif
|
|
|
|
//创建libevent上下文
|
|
event_base* base = event_base_new();
|
|
if (base) {
|
|
std::cout << "test server" << "\n";
|
|
}
|
|
|
|
|
|
sockaddr_in sin;
|
|
memset(&sin, 0, sizeof(sin));
|
|
sin.sin_family = AF_INET;
|
|
sin.sin_port = htons(SPORT);
|
|
|
|
//socket,bind listen 绑定事件
|
|
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)
|
|
);
|
|
|
|
if (base)
|
|
event_base_dispatch(base); //事件分发处理
|
|
if (ev)
|
|
evconnlistener_free(ev); //清理
|
|
if (base)
|
|
event_base_free(base);
|
|
|
|
#if _WIN32
|
|
WSACleanup();
|
|
#endif // _WIN32
|
|
|
|
|
|
|
|
return 0;
|
|
}
|
|
|
|
|