六,监听端口-接受外部连接。
在IO复用机制了解之后,其它就容易明白了。比如在监听之后,如果文件描述符有数据可以读,则说明有外部连接请求接入,这时调用_mio_accept
- static void _mio_accept(mio_t m, mio_fd_t fd)
- {
- struct sockaddr_storage serv_addr;
- socklen_t addrlen = (socklen_t) sizeof(serv_addr);
- int newfd;
- mio_fd_t mio_fd;
- char ip[INET6_ADDRSTRLEN];
- /* pull a socket off the accept queue and check */
- newfd = accept(fd->fd, (struct sockaddr*)&serv_addr, &addrlen);
- if(newfd <= 0) return;
- if(addrlen <= 0) {
- close(newfd);
- return;
- }
- j_inet_ntop(&serv_addr, ip, sizeof(ip));
- /* set up the entry for this new socket */
- mio_fd = _mio_setup_fd(m, newfd, FD(m,fd)->app, FD(m,fd)->arg);
- /* tell the app about the new socket, if they reject it clean up */
- if (ACT(m, mio_fd, action_ACCEPT, ip))
- {
- mio_debug(ZONE, "accept was rejected for %s:%d", ip, newfd);
- MIO_REMOVE_FD(m, FD(m,mio_fd));
- /* close the socket, and reset all memory */
- close(newfd);
- MIO_FREE_FD(m, mio_fd);
- }
- return;
- }
这个也是比较容易理解的,在accept之后,调用_mio_setup_fd,这个函数也是将accept返回的SOCKET文件描述符和mio_st结构关联起来,其实就是和epoll结构关联起来,将新连接加入到epoll的监听队列。
- static mio_fd_t _mio_setup_fd(mio_t m, int fd, mio_handler_t app, void *arg)
- {
- int flags;
- mio_fd_t mio_fd;
- mio_fd = MIO_ALLOC_FD(m, fd);
- /* ok to process this one, welcome to the family */
- FD(m,mio_fd)->type = type_NORMAL;
- FD(m,mio_fd)->app = app;
- FD(m,mio_fd)->arg = arg;
- /* set the socket to non-blocking */
- #if defined(HAVE_FCNTL)
- flags = fcntl(fd, F_GETFL);
- flags |= O_NONBLOCK;
- fcntl(fd, F_SETFL, flags);
- #elif defined(HAVE_IOCTL)
- flags = 1;
- ioctl(fd, FIONBIO, &flags);
- #endif
- return mio_fd;
- }
七,读数据
在有数据读写之后,都是通过 ACT(m, fd, action_WRITE, NULL)宏调用用户的自定义数据处理回调。
