libevent简述
一、简述
https://github.com/libevent/libevent
http://www.wangafu.net/~nickm/libevent-book/
http://www.wangafu.net/~nickm/libevent-2.1/doxygen/html/
http://www.wangafu.net/~nickm/libevent-1.4/doxygen/html/
libevent是一个轻量级的基于事件驱动的高性能的开源网络库,并且支持多个平台,对多个平台的I/O复用技术进行了封装,当我们编译库的代码时,编译的脚本将会根据OS支持的处理事件机制,来编译相应的代码,从而在libevent接口上保持一致。
在当前的服务器上,面对的主要问题就是要能处理大量的连接。而通过libevent这个网络库,我们就可以调用它的API来很好的解决上面的问题。
问题: 如何处理多个客户端连接
解决方案1:I/O复用技术:循环、poll、select、epoll。
解决方案2:多线程技术或多进程技术
解决方案3:常用的上述二者复合使用
lievent也是采用的上述系统提供的select,poll和epoll方法来进行I/O复用,但是针对于多个系统平台上的不同的I/O复用实现方式,libevent进行了重新的封装,并提供了统一的API接口。libevent在实现上使用了事件驱动这种机制,其本质上是一种Reactor模式。
Reactor模式,是一种事件驱动机制。应用程序需要提供相应的接口并注册到Reactor上,如果相应的事件发生,Reactor将主动调用应用程序注册的接口,这些接口又称为“回调函数”。
在Libevent中也是一样,向Libevent框架注册相应的事件和回调函数;当这些事件发生时,Libevent会调用这些回调函数处理相应的事件。
lbevent的事件支持三种,分别是网络IO、定时器和信号。定时器的数据结构使用最小堆(Min Heap),以提高效率。网络IO和信号的数据结构采用了双向链表(TAILQ)。
二、bufferevent
Most of the time, an application wants to perform some amount of data buffering in addition to just responding to events. When we want to write data, for example, the usual pattern runs something like:
-
Decide that we want to write some data to a connection; put that data in a buffer.
-
Wait for the connection to become writable
-
Write as much of the data as we can
-
Remember how much we wrote, and if we still have more data to write, wait for the connection to become writable again.
This buffered IO pattern is common enough that Libevent provides a generic mechanism for it. A "bufferevent" consists of an underlying transport (like a socket), a read buffer, and a write buffer. Instead of regular events, which give callbacks when the underlying transport is ready to be read or written, a bufferevent invokes its user-supplied callbacks when it has read or written enough data.
参考:
1. Libevent核心原理