libevent简单应用_2

目的:测试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()
{
	
	/*建立event_base数据结构 */
	struct event_base *base = event_base_new();
	if(!base)
	{
		printf("Could not initialize libevent!\n");	
		return 1;
	}

	/*建立网络连接 */
     evutil_socket_t listen_fd, connfd;
	socklen_t clilen;
	struct sockaddr_in cliaddr, serveraddr;
	
	listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	
	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(9527);
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	bind(listen_fd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
	
	listen(listen_fd, 10);
	
	clilen = sizeof(cliaddr);
	connfd = accept(listen_fd, (struct sockaddr*)&cliaddr, &clilen);
	

        main_loop(base, listen_fd);
        return 0;
}

你可能感兴趣的:(libevent简单应用_2)