一、libevent简介
Libevent 是一个用C语言编写的、轻量级的开源高性能网络库,主要有以下几个亮点:事件驱动( event-driven),高性能;轻量级,专注于网络,不如 ACE 那么臃肿庞大;源代码相当精炼、易读;跨平台,支持 Windows、 Linux、 *BSD 和 Mac Os;支持多种 I/O 多路复用技术, epoll、 poll、 dev/poll、 select 和 kqueue 等;支持 I/O,定时器和信号等事件;注册事件优先级。
Chromium(Google)、Memcached、NTP、HTTPSQS等著名的开源程序都使用libevent库,足见libevent的稳定。
二、libevent主要功能列表
* 事件管理包括各种IO(socket)、定时器、信号等事件,也是libevent应用最广的模块;
* 缓存管理是指evbuffer功能;
* DNS是libevent提供的一个异步DNS查询功能;
* HTTP是libevent的一个轻量级http实现,包括服务器和客户端
三、libevent应用实现Client/Server的聊天功能
* 异步socket读写,libevent简单聊天服务,C/S结构
* 包括流量统计功能
1. libevent-server.c
/*
* 异步socket读写,libevent简单聊天服务,C/S结构
* 包括流量统计功能
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
/* For inet_ntoa. */
#include <arpa/inet.h>
/* Required by event.h. */
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <err.h>
/* Easy sensible linked lists. */
#include "queue.h"
/* Libevent. */
#include <event2/bufferevent.h>
#include <event2/bufferevent_struct.h>
#include <event2/bufferevent_compat.h>
#include <event2/event_compat.h>
#include <event2/event.h>
/* Port to listen on. */
#define SERVER_PORT 8080
/* Length of each buffer in the buffer queue. Also becomes the amount
* of data we try to read per call to read(2). */
#define BUFLEN 2048
#define PERTIME 5
/**
* 在以事件为基础的编程时,我们需要一个队列来存储要写入的数据,
* 直到libevent通知我们可以写入,才能够真正的写入数据。这个简单的buffer队列用
* q