这个例子中,我们通过event处理socket连接,并进行一些简单的数据处理。
代码如下 test_event_server.cpp:
#include <iostream>
#include <thread>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/thread.h>
#define SPORT 5001
using namespace std;
//正常断开连接、超时都会进入
void client_cb(evutil_socket_t s, short w, void *arg){
//判断超时
event* ev = (event*)arg;
if(w & EV_TIMEOUT){
cout<<"timeout"<<endl;
event_free(ev);
evutil_closesocket(s);
return;
}
//需要清理event
char buf[1024] = {0};
int len = recv(s, buf, sizeof(buf) - 1, 0);
if(len > 0){
cout<<buf<<endl;
send(s, "ok", 2, 0);
}else{
cout<<"event_free"<<endl;
event_free(ev);
evutil_closesocket(s);
}
}
void listen_cb

该示例展示了一个在Linux环境下使用event库处理socket连接的C++代码,包括监听回调函数、客户端回调函数,以及超时10秒后自动断开连接的功能。代码中讨论了水平触发和边缘触发的区别,前者会持续触发直到事件处理,后者仅触发一次。
最低0.47元/天 解锁文章
1266

被折叠的 条评论
为什么被折叠?



