bufferevent事件
1. 介绍
封装了listen、accept, bind, socket等
应用层有两个缓冲区(读/写缓冲区),每个缓冲区对应一个回调函数,此外还有一个事件的回调函数,总共3个回调函数。

下面介绍bufferevent结构体的详情。
struct bufferevent {
/** Event base for which this bufferevent was created. */
struct event_base *ev_base;
/** Pointer to a table of function pointers to set up how this
bufferevent behaves. */
const struct bufferevent_ops *be_ops;
/** A read event that triggers when a timeout has happened or a socket
is ready to read data. Only used by some subtypes of
bufferevent. */
struct event ev_read;
/** A write event that triggers when a timeout has happened or a socket
is ready to write data. Only used by some subtypes of
bufferevent. */
struct event ev_write;
/** An input buffer. Only the bufferevent is allowed to add data to
this buffer, though the user is allowed to drain it. */
struct evbuffer *input;
/** An output buffer. Only the bufferevent is allowed to drain data
from this buffer, though the user is allowed to add it. */
struct evbuffer *output;
struct event_watermark wm_read;
struct event_watermark wm_write;
bufferevent_data_cb readcb;
bufferevent_data_cb writecb;
/* This should be called 'eventcb', but renaming it would break
* backward compatibility */
bufferevent_event_cb errorcb;
void *cbarg;
struct timeval timeout_read;
struct timeval timeout_write;
/** Events that are currently enabled: currently EV_READ and EV_WRITE
are supported. */
short enabled;
};
2. 创建新的节点
struct bufferevent *
bufferevent_socket_new(struct event_base *base, evutil_socket_t fd,
int options)
parameters:
base : event_base 根节点
fd : 要初始化上树的文件描述符,如果想后面设置文件描述符可以先设置为-1
bufferevent_options :
BEV_OPT_CLOSE_ON_FREE -- If set, we close the underlying file descriptor/bufferevent/whatever when this bufferevent is freed.
BEV_OPT_THREADSAFE -- If set, and threading is enabled, operations on this bufferevent are protected by a lock
BEV_OPT_DEFER_CALLBACKS --If set, callbacks are run deferred in the event loop
BEV_OPT_UNLOCK_CALLBACKS -- If set, callbacks are executed without locks being held on the bufferevent. This option currently requires that BEV_OPT_DEFER_CALLBACKS also be set; a future version of Libevent might remove the requirement
return value:
新建节点的地址
descript:
创建基于套接字的 bufferevent(初始化bufferevent事件,创建读写缓冲区,读写事件,以及异常事件,设置输出缓冲区回调)
3. 连接服务器
连接远程服务器,当fd=-1 ,创建socket。
int
bufferevent_socket_connect(struct bufferevent *bev,
const struct sockaddr *sa, int socklen)
parameters:
bev : bufferevent节点
sa : 服务器的地址信息
socklen: 地址信息长度
return value:
0 ---成功
-1 ----失败
descript:
address 和 addrlen 参数跟标准调用 connect()的参数相同。如果还没有为 bufferevent 设置套接字,调

本文详细介绍了libevent中的bufferevent事件,包括其结构体详情、创建新节点、连接服务器、连接监听器evconnlistener的使用,以及设置回调函数和数据的发送与接收。重点讨论了evconnlistener_new_bind和evconnlistener_new的内部实现,以及如何通过bufferevent_setcb启用或禁用事件回调。
最低0.47元/天 解锁文章
737

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



