ae事件库

#ifndef __AE_H__
#define __AE_H__

#include <time.h>
#include <stdlib.h>

/*
* 事件执行状态
*/
#define AE_OK 0     // 成功
#define AE_ERR -1   // 出错

/*
* 文件事件状态
*/
#define AE_NONE 0       // 未设置
#define AE_READABLE 1   // 可读
#define AE_WRITABLE 2   // 可写

/*
* 时间处理器的执行 flags
*/
#define AE_FILE_EVENTS 1
#define AE_TIME_EVENTS 2
#define AE_ALL_EVENTS (AE_FILE_EVENTS|AE_TIME_EVENTS)
#define AE_DONT_WAIT 4

/*
* 决定时间事件是否要持续执行的 flag
*/
#define AE_NOMORE -1

/* Macros */
#define AE_NOTUSED(V) ((void) V)

/*
* 事件处理器状态
*/
struct aeEventLoop;

/* Types and data structures */
typedef void aeFileProc(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask);
typedef int aeTimeProc(struct aeEventLoop *eventLoop, long long id, void *clientData);
typedef void aeEventFinalizerProc(struct aeEventLoop *eventLoop, void *clientData);
typedef void aeBeforeSleepProc(struct aeEventLoop *eventLoop);

/* File event structure
*
* 文件事件结构
*/
typedef struct aeFileEvent {
	// 事件类型掩码,值可以是 AE_READABLE 或 AE_WRITABLE ,或者两者的或
	int mask; /* one of AE_(READABLE|WRITABLE) */
	// 写事件函数
	aeFileProc *rfileProc;
	// 读事件函数
	aeFileProc *wfileProc;
	// 多路复用库的私有数据
	void *clientData;
} aeFileEvent;

/* Time event structure
*
* 时间事件结构
*/
typedef struct aeTimeEvent {

	// 时间事件的唯一标识符
	long long id; /* time event identifier. */

	// 事件的到达时间
	long when_sec; /* seconds */
	long when_ms; /* milliseconds */

	// 事件处理函数
	aeTimeProc *timeProc;

	// 事件释放函数
	aeEventFinalizerProc *finalizerProc;

	// 多路复用库的私有数据
	void *clientData;

	// 指向下个时间事件结构,形成链表
	struct aeTimeEvent *next;

} aeTimeEvent;

/* A fired event
*
* 已就绪事件
*/
typedef struct aeFiredEvent {
	// 已就绪文件描述符
	int fd;
	// 事件类型掩码,可以是 AE_READABLE 或 AE_WRITABLE
	int mask;
} aeFiredEvent;

/* State of an event based program 
*
* 事件处理器的状态
*/
typedef struct aeEventLoop {
	// 目前已注册的最大描述符
	int maxfd;   /* highest file descriptor currently registered */
	// 目前已追踪的最大描述符
	int setsize; /* max number of file descriptors tracked */
	// 用于生成时间事件 id
	long long timeEventNextId;
	// 最后一次执行时间事件的时间
	time_t lastTime;     /* Used to detect system clock skew */
	// 已注册的文件事件
	aeFileEvent *events; /* Registered events */
	// 已就绪的文件事件
	aeFiredEvent *fired; /* Fired events */
	// 时间事件
	aeTimeEvent *timeEventHead;
	// 事件处理器的开关
	int stop;
	// 多路复用库的私有数据
	void *apidata; /* This is used for polling API specific data */
	// 在处理事件前要执行的函数
	aeBeforeSleepProc *beforesleep;
} aeEventLoop;

/* Prototypes */
aeEventLoop *aeCreateEventLoop(int setsize);
void aeDeleteEventLoop(aeEventLoop *eventLoop);
void aeStop(aeEventLoop *eventLoop);
int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
					  aeFileProc *proc, void *clientData);
void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask);
int aeGetFileEvents(aeEventLoop *eventLoop, int fd);
long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
							aeTimeProc *proc, void *clientData,
							aeEventFinalizerProc *finalizerProc);
int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id);
int aeProcessEvents(aeEventLoop *eventLoop, int flags);
int aeWait(int fd, int mask, long long milliseconds);
void aeMain(aeEventLoop *eventLoop);
char *aeGetApiName(void);
void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep);

#endif<pre name="code" class="cpp">#define HAVE_EPOLL

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <poll.h>
#include <string.h>
#include <time.h>

#include "ae.h"

/* Include the best multiplexing layer supported by this system.
* The following should be ordered by performances, descending. */
#ifdef HAVE_EVPORT
#include "ae_evport.c"
#else
#ifdef HAVE_EPOLL
#include "ae_epoll.c"
#else
#ifdef HAVE_KQUEUE
#include "ae_kqueue.c"
#else
#include "ae_select.c"
#endif
#endif
#endif

/*
* 初始化事件处理器状态
*/
aeEventLoop *aeCreateEventLoop(int setsize) {
	aeEventLoop *eventLoop;
	int i;

	// 创建事件状态结构
	if ((eventLoop = malloc(sizeof(*eventLoop))) == NULL) goto err;

	// 初始化文件事件结构和已就绪文件事件结构
	eventLoop->events = malloc(sizeof(aeFileEvent)*setsize);
	eventLoop->fired = malloc(sizeof(aeFiredEvent)*setsize);
	if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err;
	eventLoop->setsize = setsize;
	eventLoop->lastTime = time(NULL);

	// 初始化时间事件结构
	eventLoop->timeEventHead = NULL;
	eventLoop->timeEventNextId = 0;

	eventLoop->stop = 0;
	eventLoop->maxfd = -1;
	eventLoop->beforesleep = NULL;
	if (aeApiCreate(eventLoop) == -1) goto err;
	/* Events with mask == AE_NONE are not set. So let's initialize the
	* vector with it. */
	for (i = 0; i < setsize; i++)
		eventLoop->events[i].mask = AE_NONE;
	return eventLoop;

err:
	if (eventLoop) {
		free(eventLoop->events);
		free(eventLoop->fired);
		free(eventLoop);
	}
	return NULL;
}

/*
* 删除事件处理器
*/
void aeDeleteEventLoop(aeEventLoop *eventLoop) {
	aeApiFree(eventLoop);
	free(eventLoop->events);
	free(eventLoop->fired);
	free(eventLoop);
}

/*
* 停止事件处理器
*/
void aeStop(aeEventLoop *eventLoop) {
	eventLoop->stop = 1;
}

/*
* 根据 mask 参数的值,监听 fd 文件的状态,
* 当 fd 可用时,执行 proc 函数
*/
int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
					  aeFileProc *proc, void *clientData)
{
	if (fd >= eventLoop->setsize) return AE_ERR;
	aeFileEvent *fe = &eventLoop->events[fd];

	// 监听指定 fd
	if (aeApiAddEvent(eventLoop, fd, mask) == -1)
		return AE_ERR;

	// 设置文件事件类型
	fe->mask |= mask;
	if (mask & AE_READABLE) fe->rfileProc = proc;
	if (mask & AE_WRITABLE) fe->wfileProc = proc;

	fe->clientData = clientData;

	// 如果有需要,更新事件处理器的最大 fd
	if (fd > eventLoop->maxfd)
		eventLoop->maxfd = fd;

	return AE_OK;
}

/*
* 将 fd 从 mask 指定的监听队列中删除
*/
void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
{
	if (fd >= eventLoop->setsize) return;
	aeFileEvent *fe = &eventLoop->events[fd];

	// 未设置监听的事件类型,直接返回
	if (fe->mask == AE_NONE) return;

	fe->mask = fe->mask & (~mask);
	if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
		/* Update the max fd */
		int j;

		for (j = eventLoop->maxfd-1; j >= 0; j--)
			if (eventLoop->events[j].mask != AE_NONE) break;
		eventLoop->maxfd = j;
	}

	// 取消监听给定 fd
	aeApiDelEvent(eventLoop, fd, mask);
}

/*
* 获取给定 fd 正在监听的事件类型
*/
int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
	if (fd >= eventLoop->setsize) return 0;
	aeFileEvent *fe = &eventLoop->events[fd];

	return fe->mask;
}

/*
* 取出当前时间的秒和毫秒,
* 并分别将它们保存到 seconds 和 milliseconds 参数中
*/
static void aeGetTime(long *seconds, long *milliseconds)
{
	struct timeval tv;

	gettimeofday(&tv, NULL);
	*seconds = tv.tv_sec;
	*milliseconds = tv.tv_usec/1000;
}

/*
* 为当前时间加上 milliseconds 秒。
*/
static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {
	long cur_sec, cur_ms, when_sec, when_ms;

	// 获取当前时间
	aeGetTime(&cur_sec, &cur_ms);

	// 计算增加 milliseconds 之后的秒数和毫秒数
	when_sec = cur_sec + milliseconds/1000;
	when_ms = cur_ms + milliseconds%1000;

	// 进位:
	// 如果 when_ms 大于等于 1000
	// 那么将 when_sec 增大一秒
	if (when_ms >= 1000) {
		when_sec ++;
		when_ms -= 1000;
	}
	*sec = when_sec;
	*ms = when_ms;
}

/*
* 创建时间事件
*/
long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
							aeTimeProc *proc, void *clientData,
							aeEventFinalizerProc *finalizerProc)
{
	// 更新时间计数器
	long long id = eventLoop->timeEventNextId++;
	aeTimeEvent *te;

	te = malloc(sizeof(*te));
	if (te == NULL) return AE_ERR;

	te->id = id;

	// 设定处理事件的时间
	aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms);
	te->timeProc = proc;
	te->finalizerProc = finalizerProc;
	te->clientData = clientData;

	// 将新事件放入表头
	te->next = eventLoop->timeEventHead;
	eventLoop->timeEventHead = te;

	return id;
}

/*
* 删除给定 id 的时间事件
*/
int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id)
{
	aeTimeEvent *te, *prev = NULL;

	te = eventLoop->timeEventHead;
	while(te) {
		if (te->id == id) {

			if (prev == NULL)
				eventLoop->timeEventHead = te->next;
			else
				prev->next = te->next;

			if (te->finalizerProc)
				te->finalizerProc(eventLoop, te->clientData);

			free(te);

			return AE_OK;
		}
		prev = te;
		te = te->next;
	}

	return AE_ERR; /* NO event with the specified ID found */
}

/* Search the first timer to fire.
* This operation is useful to know how many time the select can be
* put in sleep without to delay any event.
* If there are no timers NULL is returned.
*
* Note that's O(N) since time events are unsorted.
* Possible optimizations (not needed by Redis so far, but...):
* 1) Insert the event in order, so that the nearest is just the head.
*    Much better but still insertion or deletion of timers is O(N).
* 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
*/
// 寻找里目前时间最近的时间事件
// 因为链表是乱序的,所以查找复杂度为 O(N)
static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop)
{
	aeTimeEvent *te = eventLoop->timeEventHead;
	aeTimeEvent *nearest = NULL;

	while(te) {
		if (!nearest || te->when_sec < nearest->when_sec ||
			(te->when_sec == nearest->when_sec &&
			te->when_ms < nearest->when_ms))
			nearest = te;
		te = te->next;
	}
	return nearest;
}

/* Process time events
*
* 处理所有已到达的时间事件
*/
static int processTimeEvents(aeEventLoop *eventLoop) {
	int processed = 0;
	aeTimeEvent *te;
	long long maxId;
	time_t now = time(NULL);

	/* If the system clock is moved to the future, and then set back to the
	* right value, time events may be delayed in a random way. Often this
	* means that scheduled operations will not be performed soon enough.
	*
	* Here we try to detect system clock skews, and force all the time
	* events to be processed ASAP when this happens: the idea is that
	* processing events earlier is less dangerous than delaying them
	* indefinitely, and practice suggests it is. */
	// 通过重置事件的运行时间,
	// 防止因时间穿插(skew)而造成的事件处理混乱
	if (now < eventLoop->lastTime) {
		te = eventLoop->timeEventHead;
		while(te) {
			te->when_sec = 0;
			te = te->next;
		}
	}
	// 更新最后一次处理时间事件的时间
	eventLoop->lastTime = now;

	te = eventLoop->timeEventHead;
	maxId = eventLoop->timeEventNextId-1;
	while(te) {
		long now_sec, now_ms;
		long long id;

		// 跳过无效事件
		if (te->id > maxId) {
			te = te->next;
			continue;
		}

		// 获取当前时间
		aeGetTime(&now_sec, &now_ms);

		// 如果当前时间等于或等于事件的执行时间,那么执行这个事件
		if (now_sec > te->when_sec ||
			(now_sec == te->when_sec && now_ms >= te->when_ms))
		{
			int retval;

			id = te->id;
			retval = te->timeProc(eventLoop, id, te->clientData);
			processed++;
			/* After an event is processed our time event list may
			* no longer be the same, so we restart from head.
			* Still we make sure to don't process events registered
			* by event handlers itself in order to don't loop forever.
			* To do so we saved the max ID we want to handle.
			*
			* FUTURE OPTIMIZATIONS:
			* Note that this is NOT great algorithmically. Redis uses
			* a single time event so it's not a problem but the right
			* way to do this is to add the new elements on head, and
			* to flag deleted elements in a special way for later
			* deletion (putting references to the nodes to delete into
			* another linked list). */

			// 记录是否有需要循环执行这个事件时间
			if (retval != AE_NOMORE) {
				// 是的, retval 毫秒之后继续执行这个时间事件
				aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);
			} else {
				// 不,将这个事件删除
				aeDeleteTimeEvent(eventLoop, id);
			}

			// 因为执行事件之后,事件列表可能已经被改变了
			// 因此需要将 te 放回表头,继续开始执行事件
			te = eventLoop->timeEventHead;
		} else {
			te = te->next;
		}
	}
	return processed;
}

/* Process every pending time event, then every pending file event
* (that may be registered by time event callbacks just processed).
*
* 处理所有已到达的时间事件,以及所有已就绪的文件事件。
*
* Without special flags the function sleeps until some file event
* fires, or when the next time event occurrs (if any).
*
* 如果不传入特殊 flags 的话,那么函数睡眠直到文件事件就绪,
* 或者下个时间事件到达(如果有的话)。
*
* If flags is 0, the function does nothing and returns.
* 如果 flags 为 0 ,那么函数不作动作,直接返回。
*
* if flags has AE_ALL_EVENTS set, all the kind of events are processed.
* 如果 flags 包含 AE_ALL_EVENTS ,所有类型的事件都会被处理。
*
* if flags has AE_FILE_EVENTS set, file events are processed.
* 如果 flags 包含 AE_FILE_EVENTS ,那么处理文件事件。
*
* if flags has AE_TIME_EVENTS set, time events are processed.
* 如果 flags 包含 AE_TIME_EVENTS ,那么处理时间事件。
*
* if flags has AE_DONT_WAIT set the function returns ASAP until all
* the events that's possible to process without to wait are processed.
* 如果 flags 包含 AE_DONT_WAIT ,
* 那么函数在处理完所有不许阻塞的事件之后,即刻返回。
*
* The function returns the number of events processed. 
* 函数的返回值为已处理事件的数量
*/
int aeProcessEvents(aeEventLoop *eventLoop, int flags)
{
	int processed = 0, numevents;

	/* Nothing to do? return ASAP */
	if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;

	/* Note that we want call select() even if there are no
	* file events to process as long as we want to process time
	* events, in order to sleep until the next time event is ready
	* to fire. */
	if (eventLoop->maxfd != -1 ||
		((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
			int j;
			aeTimeEvent *shortest = NULL;
			struct timeval tv, *tvp;

			// 获取最近的时间事件
			if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
				shortest = aeSearchNearestTimer(eventLoop);
			if (shortest) {
				// 如果时间事件存在的话
				// 那么根据最近可执行时间事件和现在时间的时间差来决定文件事件的阻塞时间
				long now_sec, now_ms;

				/* Calculate the time missing for the nearest
				* timer to fire. */
				// 计算距今最近的时间事件还要多久才能达到
				// 并将该时间距保存在 tv 结构中
				aeGetTime(&now_sec, &now_ms);
				tvp = &tv;
				tvp->tv_sec = shortest->when_sec - now_sec;
				if (shortest->when_ms < now_ms) {
					tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000;
					tvp->tv_sec --;
				} else {
					tvp->tv_usec = (shortest->when_ms - now_ms)*1000;
				}

				// 时间差小于 0 ,说明事件已经可以执行了,将秒和毫秒设为 0 (不阻塞)
				if (tvp->tv_sec < 0) tvp->tv_sec = 0;
				if (tvp->tv_usec < 0) tvp->tv_usec = 0;
			} else {

				// 执行到这一步,说明没有时间事件
				// 那么根据 AE_DONT_WAIT 是否设置来决定是否阻塞,以及阻塞的时间长度

				/* If we have to check for events but need to return
				* ASAP because of AE_DONT_WAIT we need to se the timeout
				* to zero */
				if (flags & AE_DONT_WAIT) {
					// 设置文件事件不阻塞
					tv.tv_sec = tv.tv_usec = 0;
					tvp = &tv;
				} else {
					/* Otherwise we can block */
					// 文件事件可以阻塞直到有事件到达为止
					tvp = NULL; /* wait forever */
				}
			}

			// 处理文件事件,阻塞时间由 tvp 决定
			numevents = aeApiPoll(eventLoop, tvp);
			for (j = 0; j < numevents; j++) {
				// 从已就绪数组中获取事件
				aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];

				int mask = eventLoop->fired[j].mask;
				int fd = eventLoop->fired[j].fd;
				int rfired = 0;

				/* note the fe->mask & mask & ... code: maybe an already processed
				* event removed an element that fired and we still didn't
				* processed, so we check if the event is still valid. */
				if (fe->mask & mask & AE_READABLE) {
					// 读事件
					rfired = 1; // 确保读/写事件只能执行其中一个
					fe->rfileProc(eventLoop,fd,fe->clientData,mask);
				}
				if (fe->mask & mask & AE_WRITABLE) {
					// 写事件
					if (!rfired || fe->wfileProc != fe->rfileProc)
						fe->wfileProc(eventLoop,fd,fe->clientData,mask);
				}

				processed++;
			}
	}

	/* Check time events */
	// 执行时间事件
	if (flags & AE_TIME_EVENTS)
		processed += processTimeEvents(eventLoop);

	return processed; /* return the number of processed file/time events */
}

/* Wait for millseconds until the given file descriptor becomes
* writable/readable/exception */
int aeWait(int fd, int mask, long long milliseconds) {
	struct pollfd pfd;
	int retmask = 0, retval;

	memset(&pfd, 0, sizeof(pfd));
	pfd.fd = fd;
	if (mask & AE_READABLE) pfd.events |= POLLIN;
	if (mask & AE_WRITABLE) pfd.events |= POLLOUT;

	if ((retval = poll(&pfd, 1, milliseconds))== 1) {
		if (pfd.revents & POLLIN) retmask |= AE_READABLE;
		if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE;
		if (pfd.revents & POLLERR) retmask |= AE_WRITABLE;
		if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE;
		return retmask;
	} else {
		return retval;
	}
}

// 事件处理器的主循环
void aeMain(aeEventLoop *eventLoop) {

	eventLoop->stop = 0;

	while (!eventLoop->stop) {

		// 如果有需要在事件处理前执行的函数,那么运行它
		if (eventLoop->beforesleep != NULL)
			eventLoop->beforesleep(eventLoop);

		// 开始处理事件
		aeProcessEvents(eventLoop, AE_ALL_EVENTS);
	}
}

// 返回所使用的多路复用库的名称
char *aeGetApiName(void) {
	return aeApiName();
}

// 设置处理事件前需要被执行的函数
void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) {
	eventLoop->beforesleep = beforesleep;
}

#include <sys/epoll.h>
#include "ae.h"

typedef struct aeApiState {
	int epfd;
	struct epoll_event *events;
} aeApiState;

static int aeApiCreate(aeEventLoop *eventLoop) {
	aeApiState *state = malloc(sizeof(aeApiState));

	if (!state) return -1;
	state->events = malloc(sizeof(struct epoll_event)*eventLoop->setsize);
	if (!state->events) {
		free(state);
		return -1;
	}
	state->epfd = epoll_create(1024); /* 1024 is just an hint for the kernel */
	if (state->epfd == -1) {
		free(state->events);
		free(state);
		return -1;
	}
	eventLoop->apidata = state;
	return 0;
}

static void aeApiFree(aeEventLoop *eventLoop) {
	aeApiState *state = eventLoop->apidata;

	close(state->epfd);
	free(state->events);
	free(state);
}

static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) {
	aeApiState *state = eventLoop->apidata;
	struct epoll_event ee;
	/* If the fd was already monitored for some event, we need a MOD
	* operation. Otherwise we need an ADD operation. */
	int op = eventLoop->events[fd].mask == AE_NONE ?
EPOLL_CTL_ADD : EPOLL_CTL_MOD;

	ee.events = 0;
	mask |= eventLoop->events[fd].mask; /* Merge old events */
	if (mask & AE_READABLE) ee.events |= EPOLLIN;
	if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;
	ee.data.u64 = 0; /* avoid valgrind warning */
	ee.data.fd = fd;
	if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1;
	return 0;
}

static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int delmask) {
	aeApiState *state = eventLoop->apidata;
	struct epoll_event ee;
	int mask = eventLoop->events[fd].mask & (~delmask);

	ee.events = 0;
	if (mask & AE_READABLE) ee.events |= EPOLLIN;
	if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;
	ee.data.u64 = 0; /* avoid valgrind warning */
	ee.data.fd = fd;
	if (mask != AE_NONE) {
		epoll_ctl(state->epfd,EPOLL_CTL_MOD,fd,&ee);
	} else {
		/* Note, Kernel < 2.6.9 requires a non null event pointer even for
		* EPOLL_CTL_DEL. */
		epoll_ctl(state->epfd,EPOLL_CTL_DEL,fd,&ee);
	}
}

static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {
	aeApiState *state = eventLoop->apidata;
	int retval, numevents = 0;

	retval = epoll_wait(state->epfd,state->events,eventLoop->setsize,
		tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1);
	if (retval > 0) {
		int j;

		numevents = retval;
		for (j = 0; j < numevents; j++) {
			int mask = 0;
			struct epoll_event *e = state->events+j;

			if (e->events & EPOLLIN) mask |= AE_READABLE;
			if (e->events & EPOLLOUT) mask |= AE_WRITABLE;
			if (e->events & EPOLLERR) mask |= AE_WRITABLE;
			if (e->events & EPOLLHUP) mask |= AE_WRITABLE;
			eventLoop->fired[j].fd = e->data.fd;
			eventLoop->fired[j].mask = mask;
		}
	}
	return numevents;
}

static char *aeApiName(void) {
	return "epoll";
}

#ifndef ANET_H
#define ANET_H

#define ANET_OK 0
#define ANET_ERR -1
#define ANET_ERR_LEN 256

int anetTcpConnect(char *err, char *addr, int port);
int anetTcpNonBlockConnect(char *err, char *addr, int port);
int anetUnixConnect(char *err, char *path);
int anetUnixNonBlockConnect(char *err, char *path);
int anetRead(int fd, char *buf, int count);
int anetResolve(char *err, char *host, char *ipbuf);
int anetTcpServer(char *err, int port, char *bindaddr);
int anetUnixServer(char *err, char *path, mode_t perm);
int anetTcpAccept(char *err, int serversock, char *ip, int *port);
int anetUnixAccept(char *err, int serversock);
int anetWrite(int fd, char *buf, int count);
int anetNonBlock(char *err, int fd);
int anetTcpNoDelay(char *err, int fd);
int anetTcpKeepAlive(char *err, int fd);
int anetPeerToString(int fd, char *ip, int *port);

#endif

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>

#include "anet.h"

static void anetSetError(char *err, const char *fmt, ...)
{
	va_list ap;

	if (!err) return;
	va_start(ap, fmt);
	vsnprintf(err, ANET_ERR_LEN, fmt, ap);
	va_end(ap);
}

int anetNonBlock(char *err, int fd)
{
	int flags;

	/* Set the socket nonblocking.
	* Note that fcntl(2) for F_GETFL and F_SETFL can't be
	* interrupted by a signal. */
	if ((flags = fcntl(fd, F_GETFL)) == -1) {
		anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno));
		return ANET_ERR;
	}
	if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
		anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno));
		return ANET_ERR;
	}
	return ANET_OK;
}

int anetTcpNoDelay(char *err, int fd)
{
	int yes = 1;
	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1)
	{
		anetSetError(err, "setsockopt TCP_NODELAY: %s", strerror(errno));
		return ANET_ERR;
	}
	return ANET_OK;
}

int anetSetSendBuffer(char *err, int fd, int buffsize)
{
	if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffsize, sizeof(buffsize)) == -1)
	{
		anetSetError(err, "setsockopt SO_SNDBUF: %s", strerror(errno));
		return ANET_ERR;
	}
	return ANET_OK;
}

int anetTcpKeepAlive(char *err, int fd)
{
	int yes = 1;
	if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) == -1) {
		anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
		return ANET_ERR;
	}
	return ANET_OK;
}

int anetResolve(char *err, char *host, char *ipbuf)
{
	struct sockaddr_in sa;

	sa.sin_family = AF_INET;
	if (inet_aton(host, &sa.sin_addr) == 0) {
		struct hostent *he;

		he = gethostbyname(host);
		if (he == NULL) {
			anetSetError(err, "can't resolve: %s", host);
			return ANET_ERR;
		}
		memcpy(&sa.sin_addr, he->h_addr, sizeof(struct in_addr));
	}
	strcpy(ipbuf,inet_ntoa(sa.sin_addr));
	return ANET_OK;
}

static int anetCreateSocket(char *err, int domain) {
	int s, on = 1;
	if ((s = socket(domain, SOCK_STREAM, 0)) == -1) {
		anetSetError(err, "creating socket: %s", strerror(errno));
		return ANET_ERR;
	}

	/* Make sure connection-intensive things like the redis benckmark
	* will be able to close/open sockets a zillion of times */
	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
		anetSetError(err, "setsockopt SO_REUSEADDR: %s", strerror(errno));
		return ANET_ERR;
	}
	return s;
}

#define ANET_CONNECT_NONE 0
#define ANET_CONNECT_NONBLOCK 1
static int anetTcpGenericConnect(char *err, char *addr, int port, int flags)
{
	int s;
	struct sockaddr_in sa;

	if ((s = anetCreateSocket(err,AF_INET)) == ANET_ERR)
		return ANET_ERR;

	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	if (inet_aton(addr, &sa.sin_addr) == 0) {
		struct hostent *he;

		he = gethostbyname(addr);
		if (he == NULL) {
			anetSetError(err, "can't resolve: %s", addr);
			close(s);
			return ANET_ERR;
		}
		memcpy(&sa.sin_addr, he->h_addr, sizeof(struct in_addr));
	}
	if (flags & ANET_CONNECT_NONBLOCK) {
		if (anetNonBlock(err,s) != ANET_OK)
			return ANET_ERR;
	}
	if (connect(s, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
		if (errno == EINPROGRESS &&
			flags & ANET_CONNECT_NONBLOCK)
			return s;

		anetSetError(err, "connect: %s", strerror(errno));
		close(s);
		return ANET_ERR;
	}
	return s;
}

int anetTcpConnect(char *err, char *addr, int port)
{
	return anetTcpGenericConnect(err,addr,port,ANET_CONNECT_NONE);
}

int anetTcpNonBlockConnect(char *err, char *addr, int port)
{
	return anetTcpGenericConnect(err,addr,port,ANET_CONNECT_NONBLOCK);
}

int anetUnixGenericConnect(char *err, char *path, int flags)
{
	int s;
	struct sockaddr_un sa;

	if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
		return ANET_ERR;

	sa.sun_family = AF_LOCAL;
	strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
	if (flags & ANET_CONNECT_NONBLOCK) {
		if (anetNonBlock(err,s) != ANET_OK)
			return ANET_ERR;
	}
	if (connect(s,(struct sockaddr*)&sa,sizeof(sa)) == -1) {
		if (errno == EINPROGRESS &&
			flags & ANET_CONNECT_NONBLOCK)
			return s;

		anetSetError(err, "connect: %s", strerror(errno));
		close(s);
		return ANET_ERR;
	}
	return s;
}

int anetUnixConnect(char *err, char *path)
{
	return anetUnixGenericConnect(err,path,ANET_CONNECT_NONE);
}

int anetUnixNonBlockConnect(char *err, char *path)
{
	return anetUnixGenericConnect(err,path,ANET_CONNECT_NONBLOCK);
}

/* Like read(2) but make sure 'count' is read before to return
* (unless error or EOF condition is encountered) */
int anetRead(int fd, char *buf, int count)
{
	int nread, totlen = 0;
	while(totlen != count) {
		nread = read(fd,buf,count-totlen);
		if (nread == 0) return totlen;
		if (nread == -1) return -1;
		totlen += nread;
		buf += nread;
	}
	return totlen;
}

/* Like write(2) but make sure 'count' is read before to return
* (unless error is encountered) */
int anetWrite(int fd, char *buf, int count)
{
	int nwritten, totlen = 0;
	while(totlen != count) {
		nwritten = write(fd,buf,count-totlen);
		if (nwritten == 0) return totlen;
		if (nwritten == -1) return -1;
		totlen += nwritten;
		buf += nwritten;
	}
	return totlen;
}

static int anetListen(char *err, int s, struct sockaddr *sa, socklen_t len) {
	if (bind(s,sa,len) == -1) {
		anetSetError(err, "bind: %s", strerror(errno));
		close(s);
		return ANET_ERR;
	}

	/* Use a backlog of 512 entries. We pass 511 to the listen() call because
	* the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1);
	* which will thus give us a backlog of 512 entries */
	if (listen(s, 511) == -1) {
		anetSetError(err, "listen: %s", strerror(errno));
		close(s);
		return ANET_ERR;
	}
	return ANET_OK;
}

int anetTcpServer(char *err, int port, char *bindaddr)
{
	int s;
	struct sockaddr_in sa;

	if ((s = anetCreateSocket(err,AF_INET)) == ANET_ERR)
		return ANET_ERR;

	memset(&sa,0,sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	sa.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bindaddr && inet_aton(bindaddr, &sa.sin_addr) == 0) {
		anetSetError(err, "invalid bind address");
		close(s);
		return ANET_ERR;
	}
	if (anetListen(err,s,(struct sockaddr*)&sa,sizeof(sa)) == ANET_ERR)
		return ANET_ERR;
	return s;
}

int anetUnixServer(char *err, char *path, mode_t perm)
{
	int s;
	struct sockaddr_un sa;

	if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
		return ANET_ERR;

	memset(&sa,0,sizeof(sa));
	sa.sun_family = AF_LOCAL;
	strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
	if (anetListen(err,s,(struct sockaddr*)&sa,sizeof(sa)) == ANET_ERR)
		return ANET_ERR;
	if (perm)
		chmod(sa.sun_path, perm);
	return s;
}

static int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len) {
	int fd;
	while(1) {
		fd = accept(s,sa,len);
		if (fd == -1) {
			if (errno == EINTR)
				continue;
			else {
				anetSetError(err, "accept: %s", strerror(errno));
				return ANET_ERR;
			}
		}
		break;
	}
	return fd;
}

int anetTcpAccept(char *err, int s, char *ip, int *port) {
	int fd;
	struct sockaddr_in sa;
	socklen_t salen = sizeof(sa);
	if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == ANET_ERR)
		return ANET_ERR;

	if (ip) strcpy(ip,inet_ntoa(sa.sin_addr));
	if (port) *port = ntohs(sa.sin_port);
	return fd;
}

int anetUnixAccept(char *err, int s) {
	int fd;
	struct sockaddr_un sa;
	socklen_t salen = sizeof(sa);
	if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == ANET_ERR)
		return ANET_ERR;

	return fd;
}

int anetPeerToString(int fd, char *ip, int *port) {
	struct sockaddr_in sa;
	socklen_t salen = sizeof(sa);

	if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) {
		*port = 0;
		ip[0] = '?';
		ip[1] = '\0';
		return -1;
	}
	if (ip) strcpy(ip,inet_ntoa(sa.sin_addr));
	if (port) *port = ntohs(sa.sin_port);
	return 0;
}

int anetSockName(int fd, char *ip, int *port) {
	struct sockaddr_in sa;
	socklen_t salen = sizeof(sa);

	if (getsockname(fd,(struct sockaddr*)&sa,&salen) == -1) {
		*port = 0;
		ip[0] = '?';
		ip[1] = '\0';
		return -1;
	}
	if (ip) strcpy(ip,inet_ntoa(sa.sin_addr));
	if (port) *port = ntohs(sa.sin_port);
	return 0;
}

#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include "ae.h"
#include "anet.h"

#define PORT 4444
#define MAX_LEN 1024

//存放错误信息的字符串
char g_err_string[1024];

//事件循环机制
aeEventLoop *g_event_loop = NULL;

//定时器的入口,输出一句话
int PrintTimer(struct aeEventLoop *eventLoop, long long id, void *clientData)
{
	static int i = 0;
	printf("Test Output: %d\n", i++);
	//10秒后再次执行该函数
	return 10000;
}

//停止事件循环
void StopServer()
{
	aeStop(g_event_loop);
}

void ClientClose(aeEventLoop *el, int fd, int err)
{
	//如果err为0,则说明是正常退出,否则就是异常退出
	if( 0 == err )
		printf("Client quit: %d\n", fd);
	else if( -1 == err )
		fprintf(stderr, "Client Error: %s\n", strerror(errno));

	//删除结点,关闭文件
	aeDeleteFileEvent(el, fd, AE_READABLE);
	close(fd);
}

//有数据传过来了,读取数据
void ReadFromClient(aeEventLoop *el, int fd, void *privdata, int mask)
{
	char buffer[MAX_LEN] = { 0 };
	int res;
	res = read(fd, buffer, MAX_LEN);
	if( res <= 0 )
	{
		ClientClose(el, fd, res);
	}
	else
	{
		res = write(fd, buffer, MAX_LEN);
		if( -1 == res )
			ClientClose(el, fd, res);
	}
}

//接受新连接
void AcceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask)
{
	int cfd, cport;
	char ip_addr[128] = { 0 };
	cfd = anetTcpAccept(g_err_string, fd, ip_addr, &cport);
	printf("Connected from %s:%d\n", ip_addr, cport);

	if( aeCreateFileEvent(el, cfd, AE_READABLE,
		ReadFromClient, NULL) == AE_ERR )
	{
		fprintf(stderr, "client connect fail: %d\n", fd);
		close(fd);
	}
}

int main()
{

	printf("Start\n");

	signal(SIGINT, StopServer);

	//初始化网络事件循环
	g_event_loop = aeCreateEventLoop(1024*10);

	//设置监听事件
	int fd = anetTcpServer(g_err_string, PORT, NULL);
	if( ANET_ERR == fd )
		fprintf(stderr, "Open port %d error: %s\n", PORT, g_err_string);
	if( aeCreateFileEvent(g_event_loop, fd, AE_READABLE, 
		AcceptTcpHandler, NULL) == AE_ERR )
		fprintf(stderr, "Unrecoverable error creating server.ipfd file event.");

	//设置定时事件
	aeCreateTimeEvent(g_event_loop, 1, PrintTimer, NULL, NULL);

	//开启事件循环
	aeMain(g_event_loop);

	//删除事件循环
	aeDeleteEventLoop(g_event_loop);

	printf("End\n");
	return 0;
}

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值