1. 安装
执行 yum -y install libevent-devel
当然也可用源码编译安装,从libevent http://libevent.org/ 官网下载安装,我这里选择直接安装
2. 从一个最简单的demo 开始, 代码取自 https://www.ibm.com/developerworks/aix/library/au-libev/index.html, 略有修改
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <event.h>
#define SERVER_PORT 10087
int setnonblock( int fd )
{
int flags;
flags = fcntl( fd, F_GETFL );
flags |= O_NONBLOCK;
fcntl( fd, F_SETFL, flags );
}
void socket_read_callback(int fd, short events, void *arg)
{
char msg[1000];
struct event *ev = (struct event*)arg;
int len = read(fd, msg, sizeof(msg) - 1);
if( len <= 0 )
{
printf("some error happen when read\n");
event_free(ev);
close(fd);
return ;
}
msg[len] = '\0';
printf("recv: %s", msg);
char reply_msg[1000];//= "I have recvieced the msg: ";
strcpy(reply_msg, msg);
write(fd, reply_msg, strlen(reply_msg) );
}
void socket_accept_callback( 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 event *ev = event_new(NULL, -1, 0, NULL, NULL); //创建一个新的event
//将动态创建的结构体作为event的回调参数
event_assign(ev, base, sockfd, EV_READ | EV_PERSIST, socket_read_callback, (void*)ev);
event_add(ev, NULL);
}
int main(int main, char** args)
{
int socketlisten;
struct sockaddr_in addresslisten;
struct event accept_event;
int reuse = 1;
event_init();
socketlisten = socket( AF_INET, SOCK_STREAM, 0 );
if ( socketlisten < 0 )
{
printf("Failed to create listen socket" );
return(1);
}
memset( &addresslisten, 0, sizeof(addresslisten) );
addresslisten.sin_family = AF_INET;
addresslisten.sin_addr.s_addr = INADDR_ANY;
addresslisten.sin_port = htons( SERVER_PORT );
if ( bind( socketlisten,
(struct sockaddr *) &addresslisten,
sizeof(addresslisten) ) < 0 )
{
printf("Failed to bind" );
return(1);
}
if ( listen( socketlisten, 5 ) < 0 )
{
printf("Failed to listen to socket" );
return(1);
}
setsockopt( socketlisten,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse) );
setnonblock( socketlisten );
event_set( &accept_event,socketlisten,EV_READ | EV_PERSIST, socket_accept_callback,NULL );
event_add( &accept_event,NULL );
event_dispatch();
close( socketlisten );
return(0);
}
编译
gcc echo.c -o echo -levent
运行服务器端
./echo
用telnet 模拟客户端
telnet 127.0.0.1 10086
服务器端可以看到