一.使用
1.安装库
(1).源代码安装
下载库->解压
安装源码
(2).apt/yum
命令:stuo apt install linevent-dev
2.库方法实例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <event.h>
void sig_cb(int fd,short ev,void* arg)
{
printf("sig=%d\n",fd);
}
void timeout_cb(int fd,short ev,void* arg)
{
printf("timeout\n");
}
int main()
{
struct event_base * base = event_init();
//struct event *event_new(base,SIGINT,sig_cb,NULL);
struct event * sig_ev = event_new(base,SIGINT,EV_SIGNAL|EV_PERSIST,sig_cb,NULL);
event_add(sig_ev,NULL);
struct event * time_ev=event_new(base,-1,EV_TIMEOUT,timeout_cb,NULL);
struct timeval tv={5,0};
event_add(time_ev,&tv);
event_base_dispatch(base);
event_free(time_ev);
event_free(sig_ev);
event_base_free(base);
exit(0);
}
3.检测tcp服务器
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <event.h>
int socket_init();
struct mess
{
struct event* ev;
//
};
void recv_cb(int fd, short ev, void* arg)
{
struct mess * p = (struct mess*)arg;
if ( p == NULL )
{
return ;
}
if ( ev & EV_READ)
{
char buff[128] = {0};
int n = recv(fd,buff,127,0);
if ( n == 0 )
{
//移除
event_free(p->ev);
close(fd);
free(p);
printf("client close\n");
return ;
}
printf("buff=%s\n",buff);
send(fd,"ok",2,0);
}
}
void accept_cb(int fd, short ev, void* arg)
{
struct event_base * base = (struct event_base*)arg;
if ( ev & EV_READ)
{
struct sockaddr_in caddr;
int len = sizeof(caddr);
int c = accept(fd,(struct sockaddr*)&caddr,&len);
if ( c < 0 )
{
return;
}
printf("accept accept c=%d\n",c);
struct mess * ptr = (struct mess*)malloc(sizeof(struct mess));
if( ptr == NULL )
{
return;
}
struct event * c_ev = event_new(base,c,EV_READ |EV_PERSIST,recv_cb,ptr);
if( c_ev == NULL )
{
free(ptr);
return;
}
ptr->ev = c_ev;
event_add(c_ev,NULL);
}
}
int main()
{
int sockfd = socket_init();
if ( sockfd == -1 )
{
exit(1);
}
struct event_base * base = event_init();
if ( base == NULL )
{
exit(1);
}
struct event * sock_ev = event_new(base,sockfd,EV_READ|EV_PERSIST,accept_cb,base);
if ( sock_ev == NULL )
{
exit(1);
}
event_add(sock_ev,NULL);
event_base_dispatch(base);
event_free(sock_ev);
event_base_free(base);
exit(0);
}
int socket_init()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if ( sockfd == -1 )
{
return -1;
}
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
if ( res == -1 )
{
printf("bind err\n");
return -1;
}
if( listen(sockfd,5) == -1)
{
return -1;
}
return sockfd;
}
二.Reactor模式工作流程