libevent异步IO读写操作

一、libevent简介

Libevent 是一个用C语言编写的、轻量级的开源高性能网络库,主要有以下几个亮点:事件驱动( event-driven),高性能;轻量级,专注于网络,不如 ACE 那么臃肿庞大;源代码相当精炼、易读;跨平台,支持 Windows、 Linux、 *BSD 和 Mac Os;支持多种 I/O 多路复用技术, epoll、 poll、 dev/poll、 select 和 kqueue 等;支持 I/O,定时器和信号等事件;注册事件优先级。

Chromium(Google)MemcachedNTPHTTPSQS等著名的开源程序都使用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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值