到这里整个tomevent的框架代码就结束了,那么该如何使用呢,以下是一个测试用例。使用tomevent来同时监听2个文件描述符,一个是标准输入(fd为0),另一个是提供UDP服务的一个文件描述符。
void *test(int fd, void *arg) { cout << "****************test(): fd=" << fd << endl; char buff[256]; int len = recvfrom(fd, buff, sizeof(buff), 0, NULL, NULL); if (len > 0) { buff[len] = '\0'; cout << buff << endl; } else { perror("recvfrom error:"); } cout << "****************test()**********" << endl; } void *inTest(int fd, void *arg) { cout << "****************inTest(): fd=" << fd << endl; char buff[256]; int len = read(fd, buff, sizeof(buff)); if (len > 0) { buff[len] = '\0'; cout << buff << endl; } else { perror("read stdin error:"); } cout << "****************inTest()**********" << endl; } int main(int argc, char **argv) { int listenFd = -1; int connFd = -1; struct sockaddr_in servAddr; listenFd = socket(AF_INET, SOCK_DGRAM, 0); memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(8080); servAddr.sin_addr.s_addr = INADDR_ANY; bind(listenFd, (struct sockaddr *)&servAddr, sizeof(servAddr)); listen(listenFd, 5); Event event, inEvent; EpollEvent eventBase; event.fd = listenFd; event.event = EPOLLIN; event.arg = NULL; event.callback = test; inEvent.fd = 0; inEvent.event = EPOLLIN; inEvent.arg = NULL; inEvent.callback = inTest; eventBase.addEvent(event); eventBase.addEvent(inEvent); for (; ;) { eventBase.dispatcher(); } return 0; }
以下是测试结果 ,同时提供UDP服务和响应键盘输入。