在libevent项目中我们的服务端代码可能涉及到处理超时问题,连接异常,读写异常等问题。类似与事件响应,我们在程序里可以做如下操作。
auto evc = evconnlistener_new_bind(base, ListenCB, base,
LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,
10,//listen back
(sockaddr*)&sin,
sizeof(sin));
上面的接口是调用响应事件回调函数的接口。
void ReadCB(struct bufferevent *bev, void *ctx)
{
cout << "+" << endl;
char buf[1024] = { 0 };
int len = bufferevent_read(bev, buf, sizeof(buf) - 1);
cout << buf << endl;
//插入buffer链表
bufferevent_write(bev, "ok", 3);
}
void WriteCB(struct bufferevent *bev, void *ctx)
{
cout << "[w]" << endl;
}
void EventCB(struct bufferevent *bev, short what, void *ctx)
{
cout << "[E]" << endl;
//读超时
if (what & BEV_EVENT_TIMEOUT &BEV_EVENT_READING)
{
cout << "BEV_EVENT_READING BEV_EVENT_TIMEOUT" << endl;
//读取缓冲中内容
//清理空间,关闭监听
buffereve