目录
6、如果编译后的程序提示找不到libvent的so,则创建库的链接和缓存文件
一、LIBEVENT的概述
从LAMP说起: 是一个缩写,它指一组通常一起使用来运行动态网站或者服务器的自由软件
Linux - 操作系统
Apache - 网页服务器
MySQL - 数据库管理系统(或者数据库服务器)
二、关于C10K问题
什么是C10K?
并发能力突破不了1万连接
libevent是一个轻量级的开源的高性能的事件触发的网络库,适用于windows、linux、bsd等多种平台,内部使用select、epoll、kqueue等系统调用管理事件机制。
它被众多的开源项目使用,例如大名鼎鼎的memcached等。
特点:
事件驱动,高性能;
轻量级,专注于网络(相对于ACE);
开放源码,代码相当精炼、易读;
跨平台,支持Windows、Linux、BSD和Mac OS;
支持多种I/O多路复用技术(epoll、poll、dev/poll、select和kqueue等),在不同的操作系统下,做了多路复用模型的抽象,可以选择使用不同的模型,通过事件函数提供服务;
支持I/O,定时器和信号等事件;
采用Reactor模式;
libevent是一个典型的reactor模式的实现。
普通的函数调用机制:程序调用某个函数,函数执行,程序等待,函数将结果返回给调用程序(如果含有函数返回值的话),也就是顺序执行的。
Reactor模式的基本流程:应用程序需要提供相应的接口并且注册到reactor反应器上,如果相应的事件发生的话,那么reactor将自动调用相应的注册的接口函数(类似于回调函数)通知你,所以libevent是事件触发的网络库。
三、LIBEVENT的功能
Libevent提供了事件通知,io缓存事件,定时器,超时,异步解析dns,事件驱动的http server以及一个rpc框架。
事件通知:当文件描述符可读可写时将执行回调函数。
IO缓存:缓存事件提供了输入输出缓存,能自动的读入和写入,用户不必直接操作io。
定时器:libevent提供了定时器的机制,能够在一定的时间间隔之后调用回调函数。
信号:触发信号,执行回调。
异步的dns解析:libevent提供了异步解析dns服务器的dns解析函数集。事件驱动的http服务器:libevent提供了一个简单的,可集成到应用程序中的HTTP服务器。
RPC客户端服务器框架:libevent为创建RPC服务器和客户端创建了一个RPC框架,能自动的封装和解封数据结构。
四、LIBEVENT的安装
注意:以root用户身份操作
1、下载源码包
https://github.com/libevent/libevent/releases/download/release-2.1.12-stable/libevent-2.1.12-stable.tar.gz
2、解压
tar zxvf libevent-2.1.12-stable.tar.gz
3、配置安装路径
cd libevent-2.1.12-stable
./configure --disable-openssl
4、编译并安装
make
make install
5、测试libevent是否安装成功:
# ls -la /usr/local/include | grep event
6、如果编译后的程序提示找不到libvent的so,则创建库的链接和缓存文件
ldconfig 编译选项 -levent
五、Linux下LIBEVENT主要API介绍
1、创建事件集
struct event_base *event_base_new(void);
2、创建事件
struct event event_new
(struct event_base ,evutil_socket_t ,short ,event_callback_fn, void*)
3、添加事件
int event_add(struct event * ev,const struct timeval* timeout)
4、删除事件
int event_del(struct event *)
5、事件循环
int event_base_loop(struct event_base *base, int flags)
int event_base_dispatch(struct event_base *event_base)
六、LIBEVENT的使用步骤
创建socket
创建事件集event_base
创建event(socket, EV_READ, callback1) / event(socket, EV_WRITE, callback2)
把event添加到事件集event_base
event_base_dispatch(evnet_base); event_base_loop();
注 意:
程序的最后调用event_base_dispatch(base);实现事件的循环处理
while()
{
//调用多路复用
event_base_dispatch(base);
……
}
七、LIBEVENT实例
1、使用libevent 改造epoll 范例
main.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <event.h>
#include <event2/event.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
typedef struct _ConnectStat ConnectStat;
#define BUFLEN 1024
struct _ConnectStat {
struct event* ev;
int fd;
char send_buf[BUFLEN];
//PF *handler;//不同页面的处理函数
};
//echo 服务实现相关代码
ConnectStat * stat_init(int fd);
//void accept_connection(int fd, void *data);
void accept_connection(int fd, short events, void* arg);
void do_welcome_handler(int fd, short events, void* arg);
//void do_echo_handler(int fd, void *data);
void do_echo_handler(int fd, short events, void *arg);
void do_echo_response(int fd, short events, void *arg);
struct event_base * ev_base;
void usage(const char* argv)
{
printf("%s:[ip][port]\n", argv);
}
void set_nonblock(int fd)
{
int fl = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
int startup(char* _ip, int _port) //创建一个套接字,绑定,检测服务器
{
//sock
//1.创建套接字
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("sock");
exit(2);
}
int opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
//2.填充本地 sockaddr_in 结构体(设置本地的IP地址和端口)
struct sockaddr_in local;
local.sin_port = htons(_port);
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr(_ip);
//3.bind()绑定
if (bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
{
perror("bind");
exit(3);
}
//4.listen()监听 检测服务器
if (listen(sock, 5) < 0)
{
perror("listen");
exit(4);
}
return sock; //这样的套接字返回
}
ConnectStat * stat_init(int fd) {
ConnectStat * temp = NULL;
temp = (ConnectStat *)malloc(sizeof(ConnectStat));
if (!temp) {
fprintf(stderr, "malloc failed. reason: %m\n");
return NULL;
}
memset(temp, '\0', sizeof(ConnectStat));
temp->fd = fd;
//temp->status = 0;
}
void do_welcome_handler(int fd, short events, void* arg){
const char * WELCOME= "Welcome.\n";
int wlen = strlen(WELCOME);
int n ;
ConnectStat * stat = (ConnectStat *)(arg);
if( (n = write(fd, "Welcome.\n",wlen)) != wlen ){
if(n<=0){
fprintf(stderr, "write failed[len:%d], reason: %s\n",n,strerror(errno));
}else fprintf(stderr, "send %d bytes only ,need to send %d bytes.\n",n,wlen);
}else {
//commUpdateReadHandler(fd, do_echo_handler,(void *)stat);
event_set(stat->ev, fd, EV_READ, do_echo_handler, (void *)stat);
stat->ev->ev_base = ev_base;//必须重置事件集合
event_add(stat->ev, NULL);
}
}
void do_echo_handler(int fd, short events, void *arg) {
ConnectStat * stat = (ConnectStat *)(arg);
char * p = NULL;
assert(stat!=NULL);
p = stat->send_buf;
*p++ = '-';
*p++ = '>';
ssize_t _s = read(fd, p, BUFLEN-(p-stat->send_buf)-1); //2字节"->" +字符结束符.
if (_s > 0)
{
*(p+_s) = '\0';
printf("receive from client: %s\n", p);
//_s--;
//while( _s>=0 && ( stat->send_buf[_s]=='\r' || stat->send_buf[_s]=='\n' ) ) stat->send_buf[_s]='\0';
if(!strncasecmp(p, "quit", 4)){//退出.
//comm_close(fd);
event_free(stat->ev);//自动解除监听事件,释放event
close(fd);
free(stat);
return ;
}
//write(fd,
//commUpdateWriteHandler(fd, do_echo_response, (void *)stat);
event_set(stat->ev, fd, EV_WRITE, do_echo_response, (void *)stat);
stat->ev->ev_base = ev_base;//必须重置事件集合
event_add(stat->ev, NULL);
}else if (_s == 0) //client:close
{
fprintf(stderr,"Remote connection[fd: %d] has been closed\n", fd);
event_free(stat->ev);//自动解除监听事件,释放event
close(fd);
free(stat);
}
else //err occurred. 出错处理暂时忽略
{
fprintf(stderr,"read faield[fd: %d], reason:%s [%d]\n",fd , strerror(errno), _s);
}
}
void do_echo_response(int fd, short events, void *arg) {
ConnectStat * stat = (ConnectStat *)(arg);
int len = strlen(stat->send_buf);
int _s = write(fd, stat->send_buf, len);
if(_s>0){
event_set(stat->ev, fd, EV_READ, do_echo_handler, (void *)stat);
stat->ev->ev_base = ev_base;//必须重置事件集合
event_add(stat->ev, NULL);
}else if(_s==0){
fprintf(stderr,"Remote connection[fd: %d] has been closed\n", fd);
event_free(stat->ev);//自动解除监听事件,释放event
close(fd);
free(stat);
}else {
fprintf(stderr,"read faield[fd: %d], reason:%s [%d]\n",fd ,_s ,strerror(errno));
}
}
//read()
//注册写事件
//写事件就绪
//write()
//void accept_connection(int fd, void *data){
void accept_connection(int fd, short events, void* arg){
struct sockaddr_in peer;
socklen_t len = sizeof(peer);
int new_fd = accept(fd, (struct sockaddr*)&peer, &len);
if (new_fd > 0)
{
ConnectStat *stat = stat_init(new_fd);
set_nonblock(new_fd);
printf("new client: %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));
//commUpdateWriteHandler(new_fd, do_welcome_handler, (void *)stat);
struct event *ev = event_new(ev_base, new_fd, EV_WRITE, do_welcome_handler, (void *)stat);
stat->ev = ev;
event_add(ev, NULL);
}
}
int main(int argc,char **argv){
if (argc != 3) //检测参数个数是否正确
{
usage(argv[0]);
exit(1);
}
int listen_sock = startup(argv[1], atoi(argv[2])); //创建一个绑定了本地 ip 和端口号的套接字描述符
//初始化异步事件处理框架epoll
//comm_init(102400);
ev_base = event_base_new();
ConnectStat * stat = stat_init(listen_sock);
struct event* ev_listen = event_new(ev_base, listen_sock, EV_READ|EV_PERSIST, accept_connection, NULL);
event_add(ev_listen, NULL);
//commUpdateReadHandler(listen_sock,accept_connection,(void *)stat);
/*do{
//不断循环处理事件
//comm_select(1000);
}while(1==1);*/
event_base_dispatch(ev_base);
//comm_select_shutdown();
return 0;
}
2、实现简单的客户端和服务器端通信
需求:客户端从控制台逐行输入数据,按回车键后将数据发送给服务器端,服务器端收到请求后,再将收到的数据回传给客户端显示.
client1.c
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<event.h>
#include<event2/util.h>
int connect_server(const char* server_ip, int port);
void cmd_read_data(int fd, short events, void* arg);
void socket_read_data(int fd, short events, void *arg);
int main(int argc, char** argv)
{
if( argc < 3 )
{
printf("please input 2 parameters\n");
return -1;
}
//两个参数依次是服务器端的IP地址、端口号
int sockfd = connect_server(argv[1], atoi(argv[2]));
if( sockfd == -1)
{
perror("tcp_connect error ");
return -1;
}
printf("connect to server successfully\n");
struct event_base* base = event_base_new();
struct event *ev_sockfd = event_new(base, sockfd,
EV_READ | EV_PERSIST,
socket_read_data, NULL);
event_add(ev_sockfd, NULL);
//监听终端输入事件
struct event* ev_cmd = event_new(base, STDIN_FILENO,
EV_READ | EV_PERSIST, cmd_read_data,
(void*)&sockfd);
event_add(ev_cmd, NULL);
event_base_dispatch(base);
printf("finished \n");
return 0;
}
void cmd_read_data(int fd, short events, void* arg)
{
char msg[1024];
int ret = read(fd, msg, sizeof(msg)-1);
if( ret <= 0 )
{
perror("read fail ");
exit(1);
}
int sockfd = *((int*)arg);
if(msg[ret - 1]=='\n') msg[ret - 1] = '\0';
else msg[ret] = '\0';
//把终端的消息发送给服务器端,客户端忽略性能考虑,直接利用阻塞方式发送
printf("write to server>>> [%s]\n", msg);
write(sockfd, msg, ret);
}
void socket_read_data(int fd, short events, void *arg)
{
char msg[1024];
//为了简单起见,不考虑读一半数据的情况
int len = read(fd, msg, sizeof(msg)-1);
if( len == 0 )
{
printf("connection close. exit~\n");
exit(1);
}else if(len < 0){
perror("read fail ");
return ;
}
msg[len] = '\0';
printf("recv from server<<<<< [%s] \n", msg);
}
typedef struct sockaddr SA;
int connect_server(const char* server_ip, int port)
{
int sockfd, status, save_errno;
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr) );
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
status = inet_aton(server_ip, &server_addr.sin_addr);
if( status == 0 ) //the server_ip is not valid value
{
errno = EINVAL;
return -1;
}
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if( sockfd == -1 )
return sockfd;
status = connect(sockfd, (SA*)&server_addr, sizeof(server_addr) );
if( status == -1 )
{
save_errno = errno;
close(sockfd);
errno = save_errno; //the close may be error
return -1;
}
//evutil_make_socket_nonblocking(sockfd);
return sockfd;
}
服务器端: server1.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <event.h>
#include <event2/event.h>
#include <assert.h>
#define BUFLEN 1024
typedef struct _ConnectStat {
struct event* ev;
char buf[BUFLEN];
}ConnectStat;
//echo 服务实现相关代码
ConnectStat * stat_init(int fd, struct event *ev);
void accept_connection(int fd, short events, void* arg);
void do_echo_request(int fd, short events, void *arg);
void do_echo_response(int fd, short events, void *arg);
int tcp_server_init(int port, int listen_num);
struct event_base* base;
int main(int argc, char** argv)
{
int listener = tcp_server_init(9999, 10);
if( listener == -1 )
{
perror(" tcp_server_init error ");
return -1;
}
base = event_base_new();
//添加监听客户端请求连接事件
struct event* ev_listen = event_new(base, listener, EV_READ | EV_PERSIST,
accept_connection, base);
event_add(ev_listen, NULL);
event_base_dispatch(base);
return 0;
}
ConnectStat * stat_init(int fd, struct event *ev) {
ConnectStat * temp = NULL;
temp = (ConnectStat *)malloc(sizeof(ConnectStat));
if (!temp) {
fprintf(stderr, "malloc failed. reason: %m\n");
return NULL;
}
memset(temp, '\0', sizeof(ConnectStat));
temp->ev = ev;
}
void accept_connection(int fd, short events, void* arg)
{
evutil_socket_t sockfd;
struct sockaddr_in client;
socklen_t len = sizeof(client);
sockfd = accept(fd, (struct sockaddr*)&client, &len );
evutil_make_socket_nonblocking(sockfd);
printf("accept a client %d\n", sockfd);
struct event_base* base = (struct event_base*)arg;
//仅仅是为了动态创建一个event结构体
struct event *ev = event_new(NULL, -1, 0, NULL, NULL);
ConnectStat *stat = stat_init(sockfd, ev);
//将动态创建的结构体作为event的回调参数
event_assign(ev, base, sockfd, EV_READ ,
do_echo_request, (void*)stat);
event_add(ev, NULL);
}
void do_echo_request(int fd, short events, void *arg)
{
ConnectStat *stat = (ConnectStat *)arg;
struct event *ev = stat->ev;
char *msg = stat->buf;
printf("do echo request ...\n");
int len = read(fd, msg, BUFLEN - 1);
if( len <= 0 )
{
printf("connectin close or some error happen when read\n");
event_free(ev);
close(fd);
free(stat);
return ;
}
msg[len] = '\0';
printf("recv from client<<<< %s\n", msg);
event_set(ev, fd, EV_WRITE, do_echo_response, (void*)stat);
ev->ev_base = base;
event_add(ev, NULL);
//write(fd, reply_msg, strlen(reply_msg) );
}
void do_echo_response(int fd, short events, void *arg) {
ConnectStat * stat = (ConnectStat *)(arg);
struct event *ev = NULL;
assert(stat!=NULL);
ev = stat->ev;
int len = strlen(stat->buf);
printf("write to client>>>> %s\n", stat->buf);
int _s = write(fd, stat->buf, len);
if (_s > 0)
{
printf("write successfully.\n");
}else if (_s == 0) //client:close
{
fprintf(stderr,"Remote connection[fd: %d] has been closed\n", fd);
goto ERR_EXIT;
}
else //err occurred.
{
fprintf(stderr,"read faield[fd: %d], reason:%s [%d]\n",fd , strerror(errno), _s);
goto ERR_EXIT;
}
event_set(ev, fd, EV_READ, do_echo_request, (void*)stat);
ev->ev_base = base;
event_add(ev, NULL);
return ;
ERR_EXIT:
event_free(ev);
close(fd);
free(stat);
}
typedef struct sockaddr SA;
int tcp_server_init(int port, int listen_num)
{
int errno_save;
evutil_socket_t listener;// int listener;
listener = socket(AF_INET, SOCK_STREAM, 0);
if( listener == -1 )
return -1;
//允许多次绑定同一个地址。要用在socket和bind之间
//等同于 int opt = 1;
//setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
evutil_make_listen_socket_reuseable(listener);
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(port);
if( bind(listener, (SA*)&sin, sizeof(sin)) < 0 )
goto error;
if( listen(listener, listen_num) < 0)
goto error;
//跨平台统一接口,将套接字设置为非阻塞状态
evutil_make_socket_nonblocking(listener);
return listener;
error:
errno_save = errno;
evutil_closesocket(listener);
errno = errno_save;
return -1;
}
3、使用缓冲事件
//创建bufferevent
struct bufferevent* bev = bufferevent_socket_new(base, sockfd, BEV_OPT_CLOSE_ON_FREE);
//当有数据可读或socket关闭时会调用回调函数
bufferevent_setcb(bev, server_msg_cb, NULL, event_cb, (void*)ev_cmd);
//使bufferevent 生效
bufferevent_enable(bev, EV_READ | EV_PERSIST);
//读取数据
size_t len = bufferevent_read(bev, msg, sizeof(msg));
//写数据
bufferevent_write(bev, msg, size);
server2.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <event.h>
#include <event2/event.h>
#include <assert.h>
#define BUFLEN 1024
typedef struct _ConnectStat {
//struct event* ev;
struct bufferevent* bev;
char buf[BUFLEN];
}ConnectStat;
//echo 服务实现相关代码
ConnectStat * stat_init(int fd, struct bufferevent *bev);
void accept_connection(int fd, short events, void* arg);
void do_echo_request(struct bufferevent* bev, void* arg);
void event_cb(struct bufferevent *bev, short event, void *arg);
//void do_echo_response(int fd, short events, void *arg);
int tcp_server_init(int port, int listen_num);
struct event_base* base;
int main(int argc, char** argv)
{
int listener = tcp_server_init(9999, 10);
if( listener == -1 )
{
perror(" tcp_server_init error ");
return -1;
}
base = event_base_new();
//添加监听客户端请求连接事件
struct event* ev_listen = event_new(base, listener, EV_READ | EV_PERSIST,
accept_connection, base);
event_add(ev_listen, NULL);
event_base_dispatch(base);
return 0;
}
ConnectStat * stat_init(int fd, struct bufferevent *bev) {
ConnectStat * temp = NULL;
temp = (ConnectStat *)malloc(sizeof(ConnectStat));
if (!temp) {
fprintf(stderr, "malloc failed. reason: %m\n");
return NULL;
}
memset(temp, '\0', sizeof(ConnectStat));
temp->bev = bev;
}
void accept_connection(int fd, short events, void* arg)
{
evutil_socket_t sockfd;
struct sockaddr_in client;
socklen_t len = sizeof(client);
sockfd = accept(fd, (struct sockaddr*)&client, &len );
evutil_make_socket_nonblocking(sockfd);
printf("accept a client %d\n", sockfd);
struct event_base* base = (struct event_base*)arg;
struct bufferevent* bev = bufferevent_socket_new(base, sockfd, BEV_OPT_CLOSE_ON_FREE);
ConnectStat *stat = stat_init(sockfd, bev);
bufferevent_setcb(bev, do_echo_request, NULL, event_cb, stat);
bufferevent_enable(bev, EV_READ | EV_PERSIST);
}
void do_echo_request(struct bufferevent* bev, void* arg)
{
ConnectStat *stat = (ConnectStat *)arg;
char *msg = stat->buf;
printf("do echo request ...\n");
size_t len = bufferevent_read(bev, msg, BUFLEN);
msg[len] = '\0';
printf("recv from client<<<< %s\n", msg);
bufferevent_write(bev, msg, strlen(msg));
}
void event_cb(struct bufferevent *bev, short event, void *arg)
{
ConnectStat *stat = (ConnectStat *)arg;
if (event & BEV_EVENT_EOF)
printf("connection closed\n");
else if (event & BEV_EVENT_ERROR)
printf("some other error\n");
//这将自动close套接字和free读写缓冲区
bufferevent_free(bev);
free(stat);
}
typedef struct sockaddr SA;
int tcp_server_init(int port, int listen_num)
{
int errno_save;
evutil_socket_t listener;// int listener;
listener = socket(AF_INET, SOCK_STREAM, 0);
if( listener == -1 )
return -1;
//允许多次绑定同一个地址。要用在socket和bind之间
//等同于 int opt = 1;
//setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
evutil_make_listen_socket_reuseable(listener);
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(port);
if( bind(listener, (SA*)&sin, sizeof(sin)) < 0 )
goto error;
if( listen(listener, listen_num) < 0)
goto error;
//跨平台统一接口,将套接字设置为非阻塞状态
evutil_make_socket_nonblocking(listener);
return listener;
error:
errno_save = errno;
evutil_closesocket(listener);
errno = errno_save;
return -1;
}
server3.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <event.h>
#include <event2/event.h>
#include<event2/listener.h>
#include <assert.h>
#define BUFLEN 1024
typedef struct _ConnectStat {
//struct event* ev;
struct bufferevent* bev;
char buf[BUFLEN];
}ConnectStat;
//echo 服务实现相关代码
ConnectStat * stat_init(int fd, struct bufferevent *bev);
void listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sock, int socklen, void *arg);
//accept_connection(int fd, short events, void* arg);
void do_echo_request(struct bufferevent* bev, void* arg);
void event_cb(struct bufferevent *bev, short event, void *arg);
//void do_echo_response(int fd, short events, void *arg);
int tcp_server_init(int port, int listen_num);
struct event_base* base;
int main(int argc, char** argv)
{
struct sockaddr_in sin;
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = htons(9999);
base = event_base_new();
struct evconnlistener *listener
= evconnlistener_new_bind(base, listener_cb, base,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE,
10, (struct sockaddr*)&sin,
sizeof(struct sockaddr_in));
event_base_dispatch(base);
evconnlistener_free(listener);
event_base_free(base);
return 0;
}
ConnectStat * stat_init(int fd, struct bufferevent *bev) {
ConnectStat * temp = NULL;
temp = (ConnectStat *)malloc(sizeof(ConnectStat));
if (!temp) {
fprintf(stderr, "malloc failed. reason: %m\n");
return NULL;
}
memset(temp, '\0', sizeof(ConnectStat));
temp->bev = bev;
}
/*
一个新客户端连接上服务器此函数就会被调用,当此函数被调用时,libevent已经帮我们accept了这个客户端。
该客户端的文件描述符为fd
*/
void listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sock, int socklen, void *arg)
{
printf("accept a client %d\n", fd);
struct event_base *base = (struct event_base*)arg;
//为这个客户端分配一个bufferevent
struct bufferevent *bev = bufferevent_socket_new(base, fd,
BEV_OPT_CLOSE_ON_FREE);
ConnectStat *stat = stat_init(fd, bev);
bufferevent_setcb(bev, do_echo_request, NULL, event_cb, stat);
bufferevent_enable(bev, EV_READ | EV_PERSIST);
}
void do_echo_request(struct bufferevent* bev, void* arg)
{
ConnectStat *stat = (ConnectStat *)arg;
char *msg = stat->buf;
printf("do echo request ...\n");
size_t len = bufferevent_read(bev, msg, BUFLEN);
msg[len] = '\0';
printf("recv from client<<<< %s\n", msg);
bufferevent_write(bev, msg, strlen(msg));
}
void event_cb(struct bufferevent *bev, short event, void *arg)
{
ConnectStat *stat = (ConnectStat *)arg;
if (event & BEV_EVENT_EOF)
printf("connection closed\n");
else if (event & BEV_EVENT_ERROR)
printf("some other error\n");
//这将自动close套接字和free读写缓冲区
bufferevent_free(bev);
free(stat);
}
八、信号驱动IO简介
使用信号驱动I/O时,当网络套接字可读后,内核通过发送SIGIO信号通知应用进程,于是应用可以开 始读取数据。该方式并不是异步I/O,因为实际读取数据到应用进程缓存的工作仍然是由应用自己负责的。
1、异步IO
当用户进程发起一个read操作后,内核收到该read操作后,首先它会立刻返回,所以不会对用户进程 阻塞,然后它会等待数据的准备完成,再把数据拷贝到用户内存,完成之后,它会给用户进程发送一个信号,告诉用户进程read操作已完成.