目的:测试event_base_loop()函数
方法: 作为服务器端,当有数据到来的时候,立刻关闭base
#include <event2/event.h>
#include <stdio.h>#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <string>
void cb(evutil_socket_t sock,short what,void *arg)
{
printf("function cb is called\n");
struct event_base *base=(struct event_base*)arg;
event_base_loopbreak(base);
}
void main_loop(struct event_base *base,evutil_socket_t watchdog_fd)
{
printf("function main_loop is called\n");
struct event *watchdog_event;
watchdog_event=event_new(base,watchdog_fd,EV_READ,cb,base);
event_add(watchdog_event,NULL);
event_base_dispatch(base);
}
int main()
{
struct event_base *base=event_base_new();
if(!base)
return -1;
evutil_socket_t listenfd,connfd;
socklen_t clilen;
struct sockaddr_in cliaddr,serveraddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(15000);
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(listenfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
listen(listenfd,10);
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen);
main_loop(base,connfd);
return 0;
}