├── IO多路复用之epoll总结 ├── IO多路复用之epoll总结 ├── epoll_client.cpp └── epoll_server.cpp ├── IO多路复用之poll总结 ├── IO多路复用之poll总结 ├── poll_client.cpp └── poll_server.cpp ├── IO多路复用之select总结 ├── IO多路复用之select总结 ├── select_client.cpp └── select_server.cpp ├── LICENSE ├── README.md ├── libevent.pdf ├── libevent_http.cpp ├── libevent参考手册(中文版) .pdf ├── multi_port.cpp ├── mytalk_client.cpp ├── mytalk_server.cpp ├── mytalk_server_version1.cpp ├── mytalk_server_version2.cpp └── unblockconnect.cpp /IO多路复用之epoll总结/IO多路复用之epoll总结: -------------------------------------------------------------------------------- 1 | IO多路复用之epoll总结 2 | 3 | 1、基本知识 4 | 5 |   epoll是在2.6内核中提出的,是之前的select和poll的增强版本。相对于select和poll来说,epoll更加灵活,没有描述符限制。epoll使用一个文件描述符管理多个描述符,将用户关系的文件描述符的事件存放到内核的一个事件表中,这样在用户空间和内核空间的copy只需一次。 6 | 7 | 2、epoll接口 8 | 9 |   epoll操作过程需要三个接口,分别如下: 10 | 11 | #include 12 | int epoll_create(int size); 13 | int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); 14 | int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout); 15 | (1) int epoll_create(int size); 16 |   创建一个epoll的句柄,size用来告诉内核这个监听的数目一共有多大。这个参数不同于select()中的第一个参数,给出最大监听的fd+1的值。需要注意的是,当创建好epoll句柄后,它就是会占用一个fd值,在linux下如果查看/proc/进程id/fd/,是能够看到这个fd的,所以在使用完epoll后,必须调用close()关闭,否则可能导致fd被耗尽。 17 | 18 | (2)int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); 19 |   epoll的事件注册函数,它不同与select()是在监听事件时告诉内核要监听什么类型的事件epoll的事件注册函数,它不同与select()是在监听事件时告诉内核要监听什么类型的事件,而是在这里先注册要监听的事件类型。第一个参数是epoll_create()的返回值,第二个参数表示动作,用三个宏来表示: 20 | EPOLL_CTL_ADD:注册新的fd到epfd中; 21 | EPOLL_CTL_MOD:修改已经注册的fd的监听事件; 22 | EPOLL_CTL_DEL:从epfd中删除一个fd; 23 | 第三个参数是需要监听的fd,第四个参数是告诉内核需要监听什么事,struct epoll_event结构如下: 24 | 25 | struct epoll_event { 26 | __uint32_t events; /* Epoll events */ 27 | epoll_data_t data; /* User data variable */ 28 | }; 29 | events可以是以下几个宏的集合: 30 | EPOLLIN :表示对应的文件描述符可以读(包括对端SOCKET正常关闭); 31 | EPOLLOUT:表示对应的文件描述符可以写; 32 | EPOLLPRI:表示对应的文件描述符有紧急的数据可读(这里应该表示有带外数据到来); 33 | EPOLLERR:表示对应的文件描述符发生错误; 34 | EPOLLHUP:表示对应的文件描述符被挂断; 35 | EPOLLET: 将EPOLL设为边缘触发(Edge Triggered)模式,这是相对于水平触发(Level Triggered)来说的。 36 | EPOLLONESHOT:只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里 37 | 38 | (3) int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout); 39 |   等待事件的产生,类似于select()调用。参数events用来从内核得到事件的集合,maxevents告之内核这个events有多大,这个maxevents的值不能大于创建epoll_create()时的size,参数timeout是超时时间(毫秒,0会立即返回,-1将不确定,也有说法说是永久阻塞)。该函数返回需要处理的事件数目,如返回0表示已超时。 40 | 41 | 3、工作模式 42 | 43 |   epoll对文件描述符的操作有两种模式:LT(level trigger)和ET(edge trigger)。LT模式是默认模式,LT模式与ET模式的区别如下: 44 | 45 |   LT模式:当epoll_wait检测到描述符事件发生并将此事件通知应用程序,应用程序可以不立即处理该事件。下次调用epoll_wait时,会再次响应应用程序并通知此事件。 46 | 47 |   ET模式:当epoll_wait检测到描述符事件发生并将此事件通知应用程序,应用程序必须立即处理该事件。如果不处理,下次调用epoll_wait时,不会再次响应应用程序并通知此事件。 48 | 49 |   ET模式在很大程度上减少了epoll事件被重复触发的次数,因此效率要比LT模式高。epoll工作在ET模式的时候,必须使用非阻塞套接口,以避免由于一个文件句柄的阻塞读/阻塞写操作把处理多个文件描述符的任务饿死。 50 | 51 | 4、测试程序 52 | 53 |   编写一个服务器回射程序echo,练习epoll过程。 54 | 55 | http://www.cnblogs.com/Anker/archive/2013/08/17/3263780.html 56 | -------------------------------------------------------------------------------- /IO多路复用之epoll总结/epoll_client.cpp: -------------------------------------------------------------------------------- 1 | //客户端也用epoll实现,控制STDIN_FILENO、STDOUT_FILENO、和sockfd三个描述符 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define MAXSIZE 1024 14 | #define IPADDRESS "127.0.0.1" 15 | #define SERV_PORT 8787 16 | #define FDSIZE 1024 17 | #define EPOLLEVENTS 20 18 | 19 | static void handle_connection(int sockfd); 20 | static void 21 | handle_events(int epollfd,struct epoll_event *events,int num,int sockfd,char *buf); 22 | static void do_read(int epollfd,int fd,int sockfd,char *buf); 23 | static void do_read(int epollfd,int fd,int sockfd,char *buf); 24 | static void do_write(int epollfd,int fd,int sockfd,char *buf); 25 | static void add_event(int epollfd,int fd,int state); 26 | static void delete_event(int epollfd,int fd,int state); 27 | static void modify_event(int epollfd,int fd,int state); 28 | 29 | int main(int argc,char *argv[]) 30 | { 31 | int sockfd; 32 | struct sockaddr_in servaddr; 33 | sockfd = socket(AF_INET,SOCK_STREAM,0); 34 | bzero(&servaddr,sizeof(servaddr)); 35 | servaddr.sin_family = AF_INET; 36 | servaddr.sin_port = htons(SERV_PORT); 37 | inet_pton(AF_INET,IPADDRESS,&servaddr.sin_addr); 38 | connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 39 | //处理连接 40 | handle_connection(sockfd); 41 | close(sockfd); 42 | return 0; 43 | } 44 | 45 | 46 | static void handle_connection(int sockfd) 47 | { 48 | int epollfd; 49 | struct epoll_event events[EPOLLEVENTS]; 50 | char buf[MAXSIZE]; 51 | int ret; 52 | epollfd = epoll_create(FDSIZE); 53 | add_event(epollfd,STDIN_FILENO,EPOLLIN); 54 | for ( ; ; ) 55 | { 56 | ret = epoll_wait(epollfd,events,EPOLLEVENTS,-1); 57 | handle_events(epollfd,events,ret,sockfd,buf); 58 | } 59 | close(epollfd); 60 | } 61 | 62 | static void 63 | handle_events(int epollfd,struct epoll_event *events,int num,int sockfd,char *buf) 64 | { 65 | int fd; 66 | int i; 67 | for (i = 0;i < num;i++) 68 | { 69 | fd = events[i].data.fd; 70 | if (events[i].events & EPOLLIN) 71 | do_read(epollfd,fd,sockfd,buf); 72 | else if (events[i].events & EPOLLOUT) 73 | do_write(epollfd,fd,sockfd,buf); 74 | } 75 | } 76 | 77 | static void do_read(int epollfd,int fd,int sockfd,char *buf) 78 | { 79 | int nread; 80 | nread = read(fd,buf,MAXSIZE); 81 | if (nread == -1) 82 | { 83 | perror("read error:"); 84 | close(fd); 85 | } 86 | else if (nread == 0) 87 | { 88 | fprintf(stderr,"server close.\n"); 89 | close(fd); 90 | } 91 | else 92 | { 93 | if (fd == STDIN_FILENO) 94 | add_event(epollfd,sockfd,EPOLLOUT); 95 | else 96 | { 97 | delete_event(epollfd,sockfd,EPOLLIN); 98 | add_event(epollfd,STDOUT_FILENO,EPOLLOUT); 99 | } 100 | } 101 | } 102 | 103 | static void do_write(int epollfd,int fd,int sockfd,char *buf) 104 | { 105 | int nwrite; 106 | nwrite = write(fd,buf,strlen(buf)); 107 | if (nwrite == -1) 108 | { 109 | perror("write error:"); 110 | close(fd); 111 | } 112 | else 113 | { 114 | if (fd == STDOUT_FILENO) 115 | delete_event(epollfd,fd,EPOLLOUT); 116 | else 117 | modify_event(epollfd,fd,EPOLLIN); 118 | } 119 | memset(buf,0,MAXSIZE); 120 | } 121 | 122 | static void add_event(int epollfd,int fd,int state) 123 | { 124 | struct epoll_event ev; 125 | ev.events = state; 126 | ev.data.fd = fd; 127 | epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&ev); 128 | } 129 | 130 | static void delete_event(int epollfd,int fd,int state) 131 | { 132 | struct epoll_event ev; 133 | ev.events = state; 134 | ev.data.fd = fd; 135 | epoll_ctl(epollfd,EPOLL_CTL_DEL,fd,&ev); 136 | } 137 | 138 | static void modify_event(int epollfd,int fd,int state) 139 | { 140 | struct epoll_event ev; 141 | ev.events = state; 142 | ev.data.fd = fd; 143 | epoll_ctl(epollfd,EPOLL_CTL_MOD,fd,&ev); 144 | } 145 | -------------------------------------------------------------------------------- /IO多路复用之epoll总结/epoll_server.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define IPADDRESS "127.0.0.1" 14 | #define PORT 8787 15 | #define MAXSIZE 1024 16 | #define LISTENQ 5 17 | #define FDSIZE 1000 18 | #define EPOLLEVENTS 100 19 | 20 | //函数声明 21 | //创建套接字并进行绑定 22 | static int socket_bind(const char* ip,int port); 23 | //IO多路复用epoll 24 | static void do_epoll(int listenfd); 25 | //事件处理函数 26 | static void 27 | handle_events(int epollfd,struct epoll_event *events,int num,int listenfd,char *buf); 28 | //处理接收到的连接 29 | static void handle_accpet(int epollfd,int listenfd); 30 | //读处理 31 | static void do_read(int epollfd,int fd,char *buf); 32 | //写处理 33 | static void do_write(int epollfd,int fd,char *buf); 34 | //添加事件 35 | static void add_event(int epollfd,int fd,int state); 36 | //修改事件 37 | static void modify_event(int epollfd,int fd,int state); 38 | //删除事件 39 | static void delete_event(int epollfd,int fd,int state); 40 | 41 | int main(int argc,char *argv[]) 42 | { 43 | int listenfd; 44 | listenfd = socket_bind(IPADDRESS,PORT); 45 | listen(listenfd,LISTENQ); 46 | do_epoll(listenfd); 47 | return 0; 48 | } 49 | 50 | static int socket_bind(const char* ip,int port) 51 | { 52 | int listenfd; 53 | struct sockaddr_in servaddr; 54 | listenfd = socket(AF_INET,SOCK_STREAM,0); 55 | if (listenfd == -1) 56 | { 57 | perror("socket error:"); 58 | exit(1); 59 | } 60 | bzero(&servaddr,sizeof(servaddr)); 61 | servaddr.sin_family = AF_INET; 62 | inet_pton(AF_INET,ip,&servaddr.sin_addr); 63 | servaddr.sin_port = htons(port); 64 | if (bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1) 65 | { 66 | perror("bind error: "); 67 | exit(1); 68 | } 69 | return listenfd; 70 | } 71 | 72 | static void do_epoll(int listenfd) 73 | { 74 | int epollfd; 75 | struct epoll_event events[EPOLLEVENTS]; 76 | int ret; 77 | char buf[MAXSIZE]; 78 | memset(buf,0,MAXSIZE); 79 | //创建一个描述符 80 | epollfd = epoll_create(FDSIZE); 81 | //添加监听描述符事件 82 | add_event(epollfd,listenfd,EPOLLIN); 83 | for ( ; ; ) 84 | { 85 | //获取已经准备好的描述符事件 86 | ret = epoll_wait(epollfd,events,EPOLLEVENTS,-1); 87 | handle_events(epollfd,events,ret,listenfd,buf); 88 | } 89 | close(epollfd); 90 | } 91 | 92 | static void 93 | handle_events(int epollfd,struct epoll_event *events,int num,int listenfd,char *buf) 94 | { 95 | int i; 96 | int fd; 97 | //进行选好遍历 98 | for (i = 0;i < num;i++) 99 | { 100 | fd = events[i].data.fd; 101 | //根据描述符的类型和事件类型进行处理 102 | if ((fd == listenfd) &&(events[i].events & EPOLLIN)) 103 | handle_accpet(epollfd,listenfd); 104 | else if (events[i].events & EPOLLIN) 105 | do_read(epollfd,fd,buf); 106 | else if (events[i].events & EPOLLOUT) 107 | do_write(epollfd,fd,buf); 108 | } 109 | } 110 | static void handle_accpet(int epollfd,int listenfd) 111 | { 112 | int clifd; 113 | struct sockaddr_in cliaddr; 114 | socklen_t cliaddrlen; 115 | clifd = accept(listenfd,(struct sockaddr*)&cliaddr,&cliaddrlen); 116 | if (clifd == -1) 117 | perror("accpet error:"); 118 | else 119 | { 120 | printf("accept a new client: %s:%d\n",inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port); 121 | //添加一个客户描述符和事件 122 | add_event(epollfd,clifd,EPOLLIN); 123 | } 124 | } 125 | 126 | static void do_read(int epollfd,int fd,char *buf) 127 | { 128 | int nread; 129 | nread = read(fd,buf,MAXSIZE); 130 | if (nread == -1) 131 | { 132 | perror("read error:"); 133 | close(fd); 134 | delete_event(epollfd,fd,EPOLLIN); 135 | } 136 | else if (nread == 0) 137 | { 138 | fprintf(stderr,"client close.\n"); 139 | close(fd); 140 | delete_event(epollfd,fd,EPOLLIN); 141 | } 142 | else 143 | { 144 | printf("read message is : %s",buf); 145 | //修改描述符对应的事件,由读改为写 146 | modify_event(epollfd,fd,EPOLLOUT); 147 | } 148 | } 149 | 150 | static void do_write(int epollfd,int fd,char *buf) 151 | { 152 | int nwrite; 153 | nwrite = write(fd,buf,strlen(buf)); 154 | if (nwrite == -1) 155 | { 156 | perror("write error:"); 157 | close(fd); 158 | delete_event(epollfd,fd,EPOLLOUT); 159 | } 160 | else 161 | modify_event(epollfd,fd,EPOLLIN); 162 | memset(buf,0,MAXSIZE); 163 | } 164 | 165 | static void add_event(int epollfd,int fd,int state) 166 | { 167 | struct epoll_event ev; 168 | ev.events = state; 169 | ev.data.fd = fd; 170 | epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&ev); 171 | } 172 | 173 | static void delete_event(int epollfd,int fd,int state) 174 | { 175 | struct epoll_event ev; 176 | ev.events = state; 177 | ev.data.fd = fd; 178 | epoll_ctl(epollfd,EPOLL_CTL_DEL,fd,&ev); 179 | } 180 | 181 | static void modify_event(int epollfd,int fd,int state) 182 | { 183 | struct epoll_event ev; 184 | ev.events = state; 185 | ev.data.fd = fd; 186 | epoll_ctl(epollfd,EPOLL_CTL_MOD,fd,&ev); 187 | } 188 | -------------------------------------------------------------------------------- /IO多路复用之poll总结/IO多路复用之poll总结: -------------------------------------------------------------------------------- 1 | IO多路复用之poll总结 2 | 3 | 1、基本知识 4 | 5 |   poll的机制与select类似,与select在本质上没有多大差别,管理多个描述符也是进行轮询,根据描述符的状态进行处理,但是poll没有最大文件描述符数量的限制。poll和select同样存在一个缺点就是,包含大量文件描述符的数组被整体复制于用户态和内核的地址空间之间,而不论这些文件描述符是否就绪,它的开销随着文件描述符数量的增加而线性增大。 6 | 7 | 2、poll函数 8 | 9 |   函数格式如下所示: 10 | 11 | # include 12 | int poll ( struct pollfd * fds, unsigned int nfds, int timeout); 13 | pollfd结构体定义如下: 14 | 15 | struct pollfd { 16 | int fd; /* 文件描述符 */ 17 | short events; /* 等待的事件 */ 18 | short revents; /* 实际发生了的事件 */ 19 | } ; 20 | 21 |   每一个pollfd结构体指定了一个被监视的文件描述符,可以传递多个结构体,指示poll()监视多个文件描述符。每个结构体的events域是监视该文件描述符的事件掩码,由用户来设置这个域。revents域是文件描述符的操作结果事件掩码,内核在调用返回时设置这个域。events域中请求的任何事件都可能在revents域中返回。合法的事件如下: 22 |   POLLIN         有数据可读。 23 |   POLLRDNORM      有普通数据可读。 24 |   POLLRDBAND      有优先数据可读。 25 |   POLLPRI         有紧迫数据可读。 26 |   POLLOUT       写数据不会导致阻塞。 27 |   POLLWRNORM      写普通数据不会导致阻塞。 28 |   POLLWRBAND      写优先数据不会导致阻塞。 29 |   POLLMSGSIGPOLL     消息可用。 30 | 31 | 此外,revents域中还可能返回下列事件: 32 |   POLLER   指定的文件描述符发生错误。 33 |   POLLHUP   指定的文件描述符挂起事件。 34 |   POLLNVAL  指定的文件描述符非法。 35 | 36 | 这些事件在events域中无意义,因为它们在合适的时候总是会从revents中返回。 37 | 38 |   使用poll()和select()不一样,你不需要显式地请求异常情况报告。 39 |   POLLIN | POLLPRI等价于select()的读事件,POLLOUT |POLLWRBAND等价于select()的写事件。POLLIN等价于POLLRDNORM |POLLRDBAND,而POLLOUT则等价于POLLWRNORM。例如,要同时监视一个文件描述符是否可读和可写,我们可以设置 events为POLLIN |POLLOUT。在poll返回时,我们可以检查revents中的标志,对应于文件描述符请求的events结构体。如果POLLIN事件被设置,则文件描述符可以被读取而不阻塞。如果POLLOUT被设置,则文件描述符可以写入而不导致阻塞。这些标志并不是互斥的:它们可能被同时设置,表示这个文件描述符的读取和写入操作都会正常返回而不阻塞。 40 | 41 |   timeout参数指定等待的毫秒数,无论I/O是否准备好,poll都会返回。timeout指定为负数值表示无限超时,使poll()一直挂起直到一个指定事件发生;timeout为0指示poll调用立即返回并列出准备好I/O的文件描述符,但并不等待其它的事件。这种情况下,poll()就像它的名字那样,一旦选举出来,立即返回。 42 | 43 | 44 |   返回值和错误代码 45 |   成功时,poll()返回结构体中revents域不为0的文件描述符个数;如果在超时前没有任何事件发生,poll()返回0;失败时,poll()返回-1,并设置errno为下列值之一: 46 |   EBADF   一个或多个结构体中指定的文件描述符无效。 47 |   EFAULTfds   指针指向的地址超出进程的地址空间。 48 |   EINTR     请求的事件之前产生一个信号,调用可以重新发起。 49 |   EINVALnfds  参数超出PLIMIT_NOFILE值。 50 |   ENOMEM   可用内存不足,无法完成请求。 51 | 52 | 3、测出程序 53 | 54 |   编写一个echo server程序,功能是客户端向服务器发送信息,服务器接收输出并原样发送回给客户端,客户端接收到输出到终端。 55 | 56 | 地址:http://www.cnblogs.com/Anker/archive/2013/08/15/3261006.html 57 | -------------------------------------------------------------------------------- /IO多路复用之poll总结/poll_client.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define MAXLINE 1024 12 | #define IPADDRESS "127.0.0.1" 13 | #define SERV_PORT 8787 14 | 15 | #define max(a,b) (a > b) ? a : b 16 | 17 | static void handle_connection(int sockfd); 18 | 19 | int main(int argc,char *argv[]) 20 | { 21 | int sockfd; 22 | struct sockaddr_in servaddr; 23 | sockfd = socket(AF_INET,SOCK_STREAM,0); 24 | bzero(&servaddr,sizeof(servaddr)); 25 | servaddr.sin_family = AF_INET; 26 | servaddr.sin_port = htons(SERV_PORT); 27 | inet_pton(AF_INET,IPADDRESS,&servaddr.sin_addr); 28 | connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 29 | //处理连接描述符 30 | handle_connection(sockfd); 31 | return 0; 32 | } 33 | 34 | static void handle_connection(int sockfd) 35 | { 36 | char sendline[MAXLINE],recvline[MAXLINE]; 37 | int maxfdp,stdineof; 38 | struct pollfd pfds[2]; 39 | int n; 40 | //添加连接描述符 41 | pfds[0].fd = sockfd; 42 | pfds[0].events = POLLIN; 43 | //添加标准输入描述符 44 | pfds[1].fd = STDIN_FILENO; 45 | pfds[1].events = POLLIN; 46 | for (; ;) 47 | { 48 | poll(pfds,2,-1); 49 | if (pfds[0].revents & POLLIN) 50 | { 51 | n = read(sockfd,recvline,MAXLINE); 52 | if (n == 0) 53 | { 54 | fprintf(stderr,"client: server is closed.\n"); 55 | close(sockfd); 56 | } 57 | write(STDOUT_FILENO,recvline,n); 58 | } 59 | //测试标准输入是否准备好 60 | if (pfds[1].revents & POLLIN) 61 | { 62 | n = read(STDIN_FILENO,sendline,MAXLINE); 63 | if (n == 0) 64 | { 65 | shutdown(sockfd,SHUT_WR); 66 | continue; 67 | } 68 | write(sockfd,sendline,n); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /IO多路复用之poll总结/poll_server.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define IPADDRESS "127.0.0.1" 13 | #define PORT 8787 14 | #define MAXLINE 1024 15 | #define LISTENQ 5 16 | #define OPEN_MAX 1000 17 | #define INFTIM -1 18 | 19 | //函数声明 20 | //创建套接字并进行绑定 21 | static int socket_bind(const char* ip,int port); 22 | //IO多路复用poll 23 | static void do_poll(int listenfd); 24 | //处理多个连接 25 | static void handle_connection(struct pollfd *connfds,int num); 26 | 27 | int main(int argc,char *argv[]) 28 | { 29 | int listenfd,connfd,sockfd; 30 | struct sockaddr_in cliaddr; 31 | socklen_t cliaddrlen; 32 | listenfd = socket_bind(IPADDRESS,PORT); 33 | listen(listenfd,LISTENQ); 34 | do_poll(listenfd); 35 | return 0; 36 | } 37 | 38 | static int socket_bind(const char* ip,int port) 39 | { 40 | int listenfd; 41 | struct sockaddr_in servaddr; 42 | listenfd = socket(AF_INET,SOCK_STREAM,0); 43 | if (listenfd == -1) 44 | { 45 | perror("socket error:"); 46 | exit(1); 47 | } 48 | bzero(&servaddr,sizeof(servaddr)); 49 | servaddr.sin_family = AF_INET; 50 | inet_pton(AF_INET,ip,&servaddr.sin_addr); 51 | servaddr.sin_port = htons(port); 52 | if (bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1) 53 | { 54 | perror("bind error: "); 55 | exit(1); 56 | } 57 | return listenfd; 58 | } 59 | 60 | static void do_poll(int listenfd) 61 | { 62 | int connfd,sockfd; 63 | struct sockaddr_in cliaddr; 64 | socklen_t cliaddrlen; 65 | struct pollfd clientfds[OPEN_MAX]; 66 | int maxi; 67 | int i; 68 | int nready; 69 | //添加监听描述符 70 | clientfds[0].fd = listenfd; 71 | clientfds[0].events = POLLIN; 72 | //初始化客户连接描述符 73 | for (i = 1;i < OPEN_MAX;i++) 74 | clientfds[i].fd = -1; 75 | maxi = 0; 76 | //循环处理 77 | for ( ; ; ) 78 | { 79 | //获取可用描述符的个数 80 | nready = poll(clientfds,maxi+1,INFTIM); 81 | if (nready == -1) 82 | { 83 | perror("poll error:"); 84 | exit(1); 85 | } 86 | //测试监听描述符是否准备好 87 | if (clientfds[0].revents & POLLIN) 88 | { 89 | cliaddrlen = sizeof(cliaddr); 90 | //接受新的连接 91 | if ((connfd = accept(listenfd,(struct sockaddr*)&cliaddr,&cliaddrlen)) == -1) 92 | { 93 | if (errno == EINTR) 94 | continue; 95 | else 96 | { 97 | perror("accept error:"); 98 | exit(1); 99 | } 100 | } 101 | fprintf(stdout,"accept a new client: %s:%d\n", inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port); 102 | //将新的连接描述符添加到数组中 103 | for (i = 1;i < OPEN_MAX;i++) 104 | { 105 | if (clientfds[i].fd < 0) 106 | { 107 | clientfds[i].fd = connfd; 108 | break; 109 | } 110 | } 111 | if (i == OPEN_MAX) 112 | { 113 | fprintf(stderr,"too many clients.\n"); 114 | exit(1); 115 | } 116 | //将新的描述符添加到读描述符集合中 117 | clientfds[i].events = POLLIN; 118 | //记录客户连接套接字的个数 119 | maxi = (i > maxi ? i : maxi); 120 | if (--nready <= 0) 121 | continue; 122 | } 123 | //处理客户连接 124 | handle_connection(clientfds,maxi); 125 | } 126 | } 127 | 128 | static void handle_connection(struct pollfd *connfds,int num) 129 | { 130 | int i,n; 131 | char buf[MAXLINE]; 132 | memset(buf,0,MAXLINE); 133 | for (i = 1;i <= num;i++) 134 | { 135 | if (connfds[i].fd < 0) 136 | continue; 137 | //测试客户描述符是否准备好 138 | if (connfds[i].revents & POLLIN) 139 | { 140 | //接收客户端发送的信息 141 | n = read(connfds[i].fd,buf,MAXLINE); 142 | if (n == 0) 143 | { 144 | close(connfds[i].fd); 145 | connfds[i].fd = -1; 146 | continue; 147 | } 148 | // printf("read msg is: "); 149 | write(STDOUT_FILENO,buf,n); 150 | //向客户端发送buf 151 | write(connfds[i].fd,buf,n); 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /IO多路复用之select总结/IO多路复用之select总结: -------------------------------------------------------------------------------- 1 | IO多路复用之select总结 2 | 3 | 1、基本概念 4 | 5 |   IO多路复用是指内核一旦发现进程指定的一个或者多个IO条件准备读取,它就通知该进程。IO多路复用适用如下场合: 6 | 7 |   (1)当客户处理多个描述字时(一般是交互式输入和网络套接口),必须使用I/O复用。 8 | 9 |   (2)当一个客户同时处理多个套接口时,而这种情况是可能的,但很少出现。 10 | 11 |   (3)如果一个TCP服务器既要处理监听套接口,又要处理已连接套接口,一般也要用到I/O复用。 12 | 13 |   (4)如果一个服务器即要处理TCP,又要处理UDP,一般要使用I/O复用。 14 | 15 |   (5)如果一个服务器要处理多个服务或多个协议,一般要使用I/O复用。 16 | 17 |   与多进程和多线程技术相比,I/O多路复用技术的最大优势是系统开销小,系统不必创建进程/线程,也不必维护这些进程/线程,从而大大减小了系统的开销。 18 | 19 | 2、select函数 20 | 21 |   该函数准许进程指示内核等待多个事件中的任何一个发送,并只在有一个或多个事件发生或经历一段指定的时间后才唤醒。函数原型如下: 22 | 23 | #include 24 | #include 25 | 26 | int select(int maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,const struct timeval *timeout) 27 | 返回值:就绪描述符的数目,超时返回0,出错返回-1 28 | 函数参数介绍如下: 29 | 30 | (1)第一个参数maxfdp1指定待测试的描述字个数,它的值是待测试的最大描述字加1(因此把该参数命名为maxfdp1),描述字0、1、2...maxfdp1-1均将被测试。 31 | 32 | 因为文件描述符是从0开始的。 33 | 34 | (2)中间的三个参数readset、writeset和exceptset指定我们要让内核测试读、写和异常条件的描述字。如果对某一个的条件不感兴趣,就可以把它设为空指针。struct fd_set可以理解为一个集合,这个集合中存放的是文件描述符,可通过以下四个宏进行设置: 35 | 36 | void FD_ZERO(fd_set *fdset); //清空集合 37 | 38 | void FD_SET(int fd, fd_set *fdset); //将一个给定的文件描述符加入集合之中 39 | 40 | void FD_CLR(int fd, fd_set *fdset); //将一个给定的文件描述符从集合中删除 41 | 42 | int FD_ISSET(int fd, fd_set *fdset); // 检查集合中指定的文件描述符是否可以读写 43 | 44 | (3)timeout告知内核等待所指定描述字中的任何一个就绪可花多少时间。其timeval结构用于指定这段时间的秒数和微秒数。 45 | 46 | struct timeval{ 47 | 48 | long tv_sec; //seconds 49 | 50 | long tv_usec; //microseconds 51 | 52 | }; 53 | 54 | 这个参数有三种可能: 55 | 56 | (1)永远等待下去:仅在有一个描述字准备好I/O时才返回。为此,把该参数设置为空指针NULL。 57 | 58 | (2)等待一段固定时间:在有一个描述字准备好I/O时返回,但是不超过由该参数所指向的timeval结构中指定的秒数和微秒数。 59 | 60 | (3)根本不等待:检查描述字后立即返回,这称为轮询。为此,该参数必须指向一个timeval结构,而且其中的定时器值必须为0。 61 | 62 | 63 | 64 | 3、测试程序 65 | 66 |   写一个TCP回射程序,程序的功能是:客户端向服务器发送信息,服务器接收并原样发送给客户端,客户端显示出接收到的信息。 67 | 68 | 地址:http://www.cnblogs.com/Anker/archive/2013/08/14/3258674.html 69 | -------------------------------------------------------------------------------- /IO多路复用之select总结/select_client.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define MAXLINE 1024 13 | #define IPADDRESS "127.0.0.1" 14 | #define SERV_PORT 8787 15 | 16 | #define max(a,b) (a > b) ? a : b 17 | 18 | static void handle_recv_msg(int sockfd, char *buf) 19 | { 20 | printf("client recv msg is:%s\n", buf); 21 | sleep(5); 22 | write(sockfd, buf, strlen(buf) +1); 23 | } 24 | 25 | static void handle_connection(int sockfd) 26 | { 27 | char sendline[MAXLINE],recvline[MAXLINE]; 28 | int maxfdp,stdineof; 29 | fd_set readfds; 30 | int n; 31 | struct timeval tv; 32 | int retval = 0; 33 | 34 | while (1) { 35 | 36 | FD_ZERO(&readfds); 37 | FD_SET(sockfd,&readfds); 38 | maxfdp = sockfd; 39 | 40 | tv.tv_sec = 5; 41 | tv.tv_usec = 0; 42 | 43 | retval = select(maxfdp+1,&readfds,NULL,NULL,&tv); 44 | 45 | if (retval == -1) { 46 | return ; 47 | } 48 | 49 | if (retval == 0) { 50 | printf("client timeout.\n"); 51 | continue; 52 | } 53 | 54 | if (FD_ISSET(sockfd, &readfds)) { 55 | n = read(sockfd,recvline,MAXLINE); 56 | if (n <= 0) { 57 | fprintf(stderr,"client: server is closed.\n"); 58 | close(sockfd); 59 | FD_CLR(sockfd,&readfds); 60 | return; 61 | } 62 | 63 | handle_recv_msg(sockfd, recvline); 64 | } 65 | } 66 | } 67 | 68 | int main(int argc,char *argv[]) 69 | { 70 | int sockfd; 71 | struct sockaddr_in servaddr; 72 | 73 | sockfd = socket(AF_INET,SOCK_STREAM,0); 74 | 75 | bzero(&servaddr,sizeof(servaddr)); 76 | servaddr.sin_family = AF_INET; 77 | servaddr.sin_port = htons(SERV_PORT); 78 | inet_pton(AF_INET,IPADDRESS,&servaddr.sin_addr); 79 | 80 | int retval = 0; 81 | retval = connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 82 | if (retval < 0) { 83 | fprintf(stderr, "connect fail,error:%s\n", strerror(errno)); 84 | return -1; 85 | } 86 | 87 | printf("client send to server .\n"); 88 | write(sockfd, "hello server", 32); 89 | 90 | handle_connection(sockfd); 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /IO多路复用之select总结/select_server.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #define IPADDR "127.0.0.1" 15 | #define PORT 8787 16 | #define MAXLINE 1024 17 | #define LISTENQ 5 18 | #define SIZE 10 19 | 20 | 21 | typedef struct server_context_st 22 | { 23 | int cli_cnt; /*客户端个数*/ 24 | int clifds[SIZE]; /*客户端的个数*/ 25 | fd_set allfds; /*句柄集合*/ 26 | int maxfd; /*句柄最大值*/ 27 | } server_context_st; 28 | 29 | 30 | static server_context_st *s_srv_ctx = NULL; 31 | 32 | 33 | /*=========================================================================== 34 | * ==========================================================================*/ 35 | static int create_server_proc(const char* ip,int port) 36 | { 37 | int fd; 38 | struct sockaddr_in servaddr; 39 | fd = socket(AF_INET, SOCK_STREAM,0); 40 | if (fd == -1) { 41 | fprintf(stderr, "create socket fail,erron:%d,reason:%s\n", 42 | errno, strerror(errno)); 43 | return -1; 44 | } 45 | 46 | int yes = 1; 47 | if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { 48 | return -1; 49 | } 50 | 51 | int reuse = 1; 52 | if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) { 53 | return -1; 54 | } 55 | 56 | bzero(&servaddr,sizeof(servaddr)); 57 | servaddr.sin_family = AF_INET; 58 | inet_pton(AF_INET,ip,&servaddr.sin_addr); 59 | servaddr.sin_port = htons(port); 60 | 61 | if (bind(fd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1) { 62 | perror("bind error: "); 63 | return -1; 64 | } 65 | 66 | listen(fd,LISTENQ); 67 | 68 | return fd; 69 | } 70 | 71 | static int accept_client_proc(int srvfd) 72 | { 73 | struct sockaddr_in cliaddr; 74 | socklen_t cliaddrlen; 75 | cliaddrlen = sizeof(cliaddr); 76 | int clifd = -1; 77 | 78 | printf("accpet clint proc is called.\n"); 79 | 80 | ACCEPT: 81 | clifd = accept(srvfd,(struct sockaddr*)&cliaddr,&cliaddrlen); 82 | 83 | if (clifd == -1) { 84 | if (errno == EINTR) { 85 | goto ACCEPT; 86 | } else { 87 | fprintf(stderr, "accept fail,error:%s\n", strerror(errno)); 88 | return -1; 89 | } 90 | } 91 | 92 | fprintf(stdout, "accept a new client: %s:%d\n", 93 | inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port); 94 | 95 | //将新的连接描述符添加到数组中 96 | int i = 0; 97 | for (i = 0; i < SIZE; i++) { 98 | if (s_srv_ctx->clifds[i] < 0) { 99 | s_srv_ctx->clifds[i] = clifd; 100 | s_srv_ctx->cli_cnt++; 101 | break; 102 | } 103 | } 104 | 105 | if (i == SIZE) { 106 | fprintf(stderr,"too many clients.\n"); 107 | return -1; 108 | } 109 | 110 | } 111 | 112 | static int handle_client_msg(int fd, char *buf) 113 | { 114 | assert(buf); 115 | 116 | printf("recv buf is :%s\n", buf); 117 | 118 | write(fd, buf, strlen(buf) +1); 119 | 120 | return 0; 121 | } 122 | 123 | static void recv_client_msg(fd_set *readfds) 124 | { 125 | int i = 0, n = 0; 126 | int clifd; 127 | char buf[MAXLINE] = {0}; 128 | for (i = 0;i <= s_srv_ctx->cli_cnt;i++) { 129 | clifd = s_srv_ctx->clifds[i]; 130 | if (clifd < 0) { 131 | continue; 132 | } 133 | 134 | if (FD_ISSET(clifd, readfds)) { 135 | //接收客户端发送的信息 136 | n = read(clifd, buf, MAXLINE); 137 | if (n <= 0) { 138 | FD_CLR(clifd, &s_srv_ctx->allfds); 139 | close(clifd); 140 | s_srv_ctx->clifds[i] = -1; 141 | continue; 142 | } 143 | 144 | handle_client_msg(clifd, buf); 145 | } 146 | } 147 | } 148 | static void handle_client_proc(int srvfd) 149 | { 150 | int clifd = -1; 151 | int retval = 0; 152 | fd_set *readfds = &s_srv_ctx->allfds; 153 | struct timeval tv; 154 | int i = 0; 155 | 156 | while (1) { 157 | 158 | /*每次调用select前都要重新设置文件描述符和时间,因为事件发生后,文件描述符和时间都被内核修改啦*/ 159 | /*添加监听套接字*/ 160 | FD_ZERO(readfds); 161 | FD_SET(srvfd, readfds); 162 | s_srv_ctx->maxfd = srvfd; 163 | 164 | tv.tv_sec = 30; 165 | tv.tv_usec = 0; 166 | 167 | /*添加客户端套接字*/ 168 | for (i = 0; i < s_srv_ctx->cli_cnt; i++) { 169 | clifd = s_srv_ctx->clifds[i]; 170 | FD_SET(clifd, readfds); 171 | s_srv_ctx->maxfd = (clifd > s_srv_ctx->maxfd ? clifd : s_srv_ctx->maxfd); 172 | } 173 | 174 | retval = select(s_srv_ctx->maxfd + 1, readfds, NULL, NULL, &tv); 175 | 176 | if (retval == -1) { 177 | fprintf(stderr, "select error:%s.\n", strerror(errno)); 178 | return; 179 | } 180 | 181 | if (retval == 0) { 182 | fprintf(stdout, "select is timeout.\n"); 183 | continue; 184 | } 185 | 186 | if (FD_ISSET(srvfd, readfds)) { 187 | /*监听客户端请求*/ 188 | accept_client_proc(srvfd); 189 | } else { 190 | /*接受处理客户端消息*/ 191 | recv_client_msg(readfds); 192 | } 193 | } 194 | } 195 | 196 | 197 | static void server_uninit() 198 | { 199 | if (s_srv_ctx) { 200 | free(s_srv_ctx); 201 | s_srv_ctx = NULL; 202 | } 203 | } 204 | 205 | static int server_init() 206 | { 207 | s_srv_ctx = (server_context_st *)malloc(sizeof(server_context_st)); 208 | if (s_srv_ctx == NULL) { 209 | return -1; 210 | } 211 | 212 | memset(s_srv_ctx, 0, sizeof(server_context_st)); 213 | 214 | int i = 0; 215 | for (;i < SIZE; i++) { 216 | s_srv_ctx->clifds[i] = -1; 217 | } 218 | 219 | return 0; 220 | } 221 | 222 | int main(int argc,char *argv[]) 223 | { 224 | int srvfd; 225 | 226 | if (server_init() < 0) { 227 | return -1; 228 | } 229 | 230 | srvfd = create_server_proc(IPADDR, PORT); 231 | if (srvfd < 0) { 232 | fprintf(stderr, "socket create or bind fail.\n"); 233 | goto err; 234 | } 235 | 236 | handle_client_proc(srvfd); 237 | 238 | return 0; 239 | 240 | err: 241 | server_uninit(); 242 | return -1; 243 | } 244 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MulticsIO 2 | 该项目为学习Linux网络编程所编写的一些小程序。 3 | * unblockconnect.cpp:是非阻塞connect的一种实现方式。 4 | * mytalk_client.cpp、mytalk_server_version1.cpp:是一个简易的聊天室程序。 5 | * multi_port.cpp:是同时处理TCP请求和UDB请求的回射服务器。 6 | * mytalk_server_version2.cpp:后续使用共享内存实现的聊天室服务器程序。 7 | * libevent_http.cpp:基于 http 协议的服务器代码。 8 | 9 | **注:** 10 | * 列出一些自己觉得不错的博客(关于Select,poll,epoll和libevent网络库)。 11 | * 源文件包括学习libevent的两个文件,一个是中文的手册,一个是“传智播客C++学院”的学习资料。 12 | 13 | **参考博客:** 14 | * 聊聊同步、异步、阻塞与非阻塞:http://www.jianshu.com/p/aed6067eeac9 15 | * 聊聊Linux 五种IO模型:http://www.jianshu.com/p/486b0965c296 16 | * 聊聊IO多路复用之select、poll、epoll详解:http://www.jianshu.com/p/dfd940e7fca2 17 | * Linux IO模式及 select、poll、epoll详解:https://segmentfault.com/a/1190000003063859 18 | * I/O并发编程总结:https://segmentfault.com/a/1190000004909797 19 | * Libevent 官方文档学习笔记(1. libevent_core部分):https://segmentfault.com/a/1190000005594871 20 | * Libevent 官方文档学习笔记(2. bufferevent部分):https://segmentfault.com/a/1190000005601925 21 | * Libevent 官方文档学习笔记(3. evbuffer部分):https://segmentfault.com/a/1190000005867855 22 | 23 | ## License 24 | 25 | MulticsIO source code is licensed under the 26 | [Apache Licence, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) 27 | -------------------------------------------------------------------------------- /libevent.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MulticsYin/MulticsIO/260e3ee31dde9f76313fc46cdcf42968180af215/libevent.pdf -------------------------------------------------------------------------------- /libevent_http.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include // 必须包含 libevent的核心头文件 6 | #include // libevent 提供的http 服务的头文件 7 | #include 8 | void http_req(struct evhttp_request *req,void *arg) 9 | { 10 | char output[2048]="\0"; 11 | char tmp[1024]; 12 | //获取 访问的请求链接 (使用 evhttp_request_uri or req->uri) 13 | const char *uri; 14 | uri = evhttp_request_get_uri(req); 15 | sprintf(tmp,"uri=%s\n",uri); 16 | strcat(output,tmp); 17 | 18 | 19 | // 把请求的链接参数 解码 20 | char *decoded_uri; 21 | decoded_uri = evhttp_decode_uri(uri); 22 | 23 | 24 | //解析url的参数 25 | struct evkeyvalq params; 26 | evhttp_parse_query(decoded_uri,?ms); 27 | sprintf(tmp,"q=%s\n",evhttp_find_header(¶ms,"usrname")); 28 | strcat(output,tmp); 29 | sprintf(tmp,"s=%s\n",evhttp_find_header(¶ms,"password")); // evhttp_find_header 是获取请求链接里特定的字段值 30 | strcat(output,tmp); 31 | free(decoded_uri); 32 | 33 | /* 34 | 这里可以做很多操作 比如 数据库存储操作 比如memcatch 缓存操作等等 35 | */ 36 | 37 | // http 协议头 38 | evhttp_add_header(req->output_headers,"Content-Type","text/plain;charset=UTF-8"); 39 | evhttp_add_header(req->output_headers,"Connection","hello world"); 40 | 41 | 42 | struct evbuffer *buf; // 字符缓冲区 43 | buf = evbuffer_new(); 44 | evbuffer_add_printf(buf,"It works !\n%s\n",output); // 把结果返回给客户端 45 | evhttp_send_reply(req,HTTP_OK,"OK",buf); 46 | evbuffer_free(buf); 47 | 48 | } 49 | int main(int argc, char *argv[]) 50 | { 51 | char *http_addr= "127.0.0.1"; 52 | char *http_port = 8080; 53 | int http_daemon = 0; 54 | int http_timeout = 120; 55 | if (httpd_daemon) 56 | { 57 | pid_t pid; 58 | pid = fork(); 59 | if (pid<0) 60 | { 61 | perror("fork failed"); 62 | exit(EXIT_FAILURE); 63 | } 64 | if (pid>0) 65 | { 66 | exit(EXIT_SUCCESS); 67 | } 68 | } 69 | event_init(); // 初始化 event_init 环境 也可以用 struct event_base *base; 70 | struct evhttp *http; // 也可以用 http = evhttp_new(base); 如果调用了 evhttp_new函数 则调用 evhttp_bind_socket 配套使用 我还没试过其他的方式 71 | // 这里直接 调用启动 http 函数 72 | http= evhttp_start(http_addr,http_port); 73 | evhttp_set_timeout(http,http_timeout); 74 | evhttp_set_gencb(http,http_req,NULL); // 加载回调 75 | event_dispatch(); 76 | evhttp_free(http); 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /libevent参考手册(中文版) .pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MulticsYin/MulticsIO/260e3ee31dde9f76313fc46cdcf42968180af215/libevent参考手册(中文版) .pdf -------------------------------------------------------------------------------- /multi_port.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #define MAX_EVENT_NUMBER 1024 16 | #define TCP_BUFFER_SIZE 512 17 | #define UDP_BUFFER_SIZE 1024 18 | 19 | int setnonblocking( int fd ) 20 | { 21 | int old_option = fcntl( fd, F_GETFL ); 22 | int new_option = old_option | O_NONBLOCK; 23 | fcntl( fd, F_SETFL, new_option ); 24 | return old_option; 25 | } 26 | 27 | void addfd( int epollfd, int fd ) 28 | { 29 | epoll_event event; 30 | event.data.fd = fd; 31 | //event.events = EPOLLIN | EPOLLET; 32 | event.events = EPOLLIN; 33 | epoll_ctl( epollfd, EPOLL_CTL_ADD, fd, &event ); 34 | setnonblocking( fd ); 35 | } 36 | 37 | int main( int argc, char* argv[] ) 38 | { 39 | if( argc <= 2 ) 40 | { 41 | printf( "usage: %s ip_address port_number\n", basename( argv[0] ) ); 42 | return 1; 43 | } 44 | const char* ip = argv[1]; 45 | int port = atoi( argv[2] ); 46 | 47 | int ret = 0; 48 | struct sockaddr_in address; 49 | bzero( &address, sizeof( address ) ); 50 | address.sin_family = AF_INET; 51 | inet_pton( AF_INET, ip, &address.sin_addr ); 52 | address.sin_port = htons( port ); 53 | 54 | int listenfd = socket( PF_INET, SOCK_STREAM, 0 ); 55 | assert( listenfd >= 0 ); 56 | 57 | ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) ); 58 | assert( ret != -1 ); 59 | 60 | ret = listen( listenfd, 5 ); 61 | assert( ret != -1 ); 62 | 63 | bzero( &address, sizeof( address ) ); 64 | address.sin_family = AF_INET; 65 | inet_pton( AF_INET, ip, &address.sin_addr ); 66 | address.sin_port = htons( port ); 67 | int udpfd = socket( PF_INET, SOCK_DGRAM, 0 ); 68 | assert( udpfd >= 0 ); 69 | 70 | ret = bind( udpfd, ( struct sockaddr* )&address, sizeof( address ) ); 71 | assert( ret != -1 ); 72 | 73 | epoll_event events[ MAX_EVENT_NUMBER ]; 74 | int epollfd = epoll_create( 5 ); 75 | assert( epollfd != -1 ); 76 | addfd( epollfd, listenfd ); 77 | addfd( epollfd, udpfd ); 78 | 79 | while( 1 ) 80 | { 81 | int number = epoll_wait( epollfd, events, MAX_EVENT_NUMBER, -1 ); 82 | if ( number < 0 ) 83 | { 84 | printf( "epoll failure\n" ); 85 | break; 86 | } 87 | 88 | for ( int i = 0; i < number; i++ ) 89 | { 90 | int sockfd = events[i].data.fd; 91 | if ( sockfd == listenfd ) 92 | { 93 | struct sockaddr_in client_address; 94 | socklen_t client_addrlength = sizeof( client_address ); 95 | int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength ); 96 | addfd( epollfd, connfd ); 97 | } 98 | else if ( sockfd == udpfd ) 99 | { 100 | char buf[ UDP_BUFFER_SIZE ]; 101 | memset( buf, '\0', UDP_BUFFER_SIZE ); 102 | struct sockaddr_in client_address; 103 | socklen_t client_addrlength = sizeof( client_address ); 104 | 105 | ret = recvfrom( udpfd, buf, UDP_BUFFER_SIZE-1, 0, ( struct sockaddr* )&client_address, &client_addrlength ); 106 | if( ret > 0 ) 107 | { 108 | sendto( udpfd, buf, UDP_BUFFER_SIZE-1, 0, ( struct sockaddr* )&client_address, client_addrlength ); 109 | } 110 | } 111 | else if ( events[i].events & EPOLLIN ) 112 | { 113 | char buf[ TCP_BUFFER_SIZE ]; 114 | while( 1 ) 115 | { 116 | memset( buf, '\0', TCP_BUFFER_SIZE ); 117 | ret = recv( sockfd, buf, TCP_BUFFER_SIZE-1, 0 ); 118 | if( ret < 0 ) 119 | { 120 | if( ( errno == EAGAIN ) || ( errno == EWOULDBLOCK ) ) 121 | { 122 | break; 123 | } 124 | close( sockfd ); 125 | break; 126 | } 127 | else if( ret == 0 ) 128 | { 129 | close( sockfd ); 130 | } 131 | else 132 | { 133 | send( sockfd, buf, ret, 0 ); 134 | } 135 | } 136 | } 137 | else 138 | { 139 | printf( "something else happened \n" ); 140 | } 141 | } 142 | } 143 | 144 | close( listenfd ); 145 | return 0; 146 | } 147 | -------------------------------------------------------------------------------- /mytalk_client.cpp: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 1 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #define BUFFER_SIZE 64 15 | 16 | int main( int argc, char* argv[] ) 17 | { 18 | if( argc <= 2 ) 19 | { 20 | printf( "usage: %s ip_address port_number\n", basename( argv[0] ) ); 21 | return 1; 22 | } 23 | const char* ip = argv[1]; 24 | int port = atoi( argv[2] ); 25 | 26 | struct sockaddr_in server_address; 27 | bzero( &server_address, sizeof( server_address ) ); 28 | server_address.sin_family = AF_INET; 29 | inet_pton( AF_INET, ip, &server_address.sin_addr ); 30 | server_address.sin_port = htons( port ); 31 | 32 | int sockfd = socket( PF_INET, SOCK_STREAM, 0 ); 33 | assert( sockfd >= 0 ); 34 | if ( connect( sockfd, ( struct sockaddr* )&server_address, sizeof( server_address ) ) < 0 ) 35 | { 36 | printf( "connection failed\n" ); 37 | close( sockfd ); 38 | return 1; 39 | } 40 | 41 | pollfd fds[2]; 42 | fds[0].fd = 0; 43 | fds[0].events = POLLIN; 44 | fds[0].revents = 0; 45 | fds[1].fd = sockfd; 46 | fds[1].events = POLLIN | POLLRDHUP; 47 | fds[1].revents = 0; 48 | char read_buf[BUFFER_SIZE]; 49 | int pipefd[2]; 50 | int ret = pipe( pipefd ); 51 | assert( ret != -1 ); 52 | 53 | while( 1 ) 54 | { 55 | ret = poll( fds, 2, -1 ); 56 | if( ret < 0 ) 57 | { 58 | printf( "poll failure\n" ); 59 | break; 60 | } 61 | 62 | if( fds[1].revents & POLLRDHUP ) 63 | { 64 | printf( "server close the connection\n" ); 65 | break; 66 | } 67 | else if( fds[1].revents & POLLIN ) 68 | { 69 | memset( read_buf, '\0', BUFFER_SIZE ); 70 | recv( fds[1].fd, read_buf, BUFFER_SIZE-1, 0 ); 71 | printf( "%s\n", read_buf ); 72 | } 73 | 74 | if( fds[0].revents & POLLIN ) 75 | { 76 | ret = splice( 0, NULL, pipefd[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE ); 77 | ret = splice( pipefd[0], NULL, sockfd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE ); 78 | } 79 | } 80 | 81 | close( sockfd ); 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /mytalk_server.cpp: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 1 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #define USER_LIMIT 5 16 | #define BUFFER_SIZE 64 17 | #define FD_LIMIT 65535 18 | 19 | struct client_data 20 | { 21 | sockaddr_in address; 22 | char* write_buf; 23 | char buf[ BUFFER_SIZE ]; 24 | }; 25 | 26 | int setnonblocking( int fd ) 27 | { 28 | int old_option = fcntl( fd, F_GETFL ); 29 | int new_option = old_option | O_NONBLOCK; 30 | fcntl( fd, F_SETFL, new_option ); 31 | return old_option; 32 | } 33 | 34 | int main( int argc, char* argv[] ) 35 | { 36 | if( argc <= 2 ) 37 | { 38 | printf( "usage: %s ip_address port_number\n", basename( argv[0] ) ); 39 | return 1; 40 | } 41 | const char* ip = argv[1]; 42 | int port = atoi( argv[2] ); 43 | 44 | int ret = 0; 45 | struct sockaddr_in address; 46 | bzero( &address, sizeof( address ) ); 47 | address.sin_family = AF_INET; 48 | inet_pton( AF_INET, ip, &address.sin_addr ); 49 | address.sin_port = htons( port ); 50 | 51 | int listenfd = socket( PF_INET, SOCK_STREAM, 0 ); 52 | assert( listenfd >= 0 ); 53 | 54 | ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) ); 55 | assert( ret != -1 ); 56 | 57 | ret = listen( listenfd, 5 ); 58 | assert( ret != -1 ); 59 | 60 | client_data* users = new client_data[FD_LIMIT]; 61 | pollfd fds[USER_LIMIT+1]; 62 | int user_counter = 0; 63 | for( int i = 1; i <= USER_LIMIT; ++i ) 64 | { 65 | fds[i].fd = -1; 66 | fds[i].events = 0; 67 | } 68 | fds[0].fd = listenfd; 69 | fds[0].events = POLLIN | POLLERR; 70 | fds[0].revents = 0; 71 | 72 | while( 1 ) 73 | { 74 | ret = poll( fds, user_counter+1, -1 ); 75 | if ( ret < 0 ) 76 | { 77 | printf( "poll failure\n" ); 78 | break; 79 | } 80 | 81 | for( int i = 0; i < user_counter+1; ++i ) 82 | { 83 | if( ( fds[i].fd == listenfd ) && ( fds[i].revents & POLLIN ) ) 84 | { 85 | struct sockaddr_in client_address; 86 | socklen_t client_addrlength = sizeof( client_address ); 87 | int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength ); 88 | if ( connfd < 0 ) 89 | { 90 | printf( "errno is: %d\n", errno ); 91 | continue; 92 | } 93 | if( user_counter >= USER_LIMIT ) 94 | { 95 | const char* info = "too many users\n"; 96 | printf( "%s", info ); 97 | send( connfd, info, strlen( info ), 0 ); 98 | close( connfd ); 99 | continue; 100 | } 101 | user_counter++; 102 | users[connfd].address = client_address; 103 | setnonblocking( connfd ); 104 | fds[user_counter].fd = connfd; 105 | fds[user_counter].events = POLLIN | POLLRDHUP | POLLERR; 106 | fds[user_counter].revents = 0; 107 | printf( "comes a new user, now have %d users\n", user_counter ); 108 | } 109 | else if( fds[i].revents & POLLERR ) 110 | { 111 | printf( "get an error from %d\n", fds[i].fd ); 112 | char errors[ 100 ]; 113 | memset( errors, '\0', 100 ); 114 | socklen_t length = sizeof( errors ); 115 | if( getsockopt( fds[i].fd, SOL_SOCKET, SO_ERROR, &errors, &length ) < 0 ) 116 | { 117 | printf( "get socket option failed\n" ); 118 | } 119 | continue; 120 | } 121 | else if( fds[i].revents & POLLRDHUP ) 122 | { 123 | users[fds[i].fd] = users[fds[user_counter].fd]; 124 | close( fds[i].fd ); 125 | fds[i] = fds[user_counter]; 126 | i--; 127 | user_counter--; 128 | printf( "a client left\n" ); 129 | } 130 | else if( fds[i].revents & POLLIN ) 131 | { 132 | int connfd = fds[i].fd; 133 | memset( users[connfd].buf, '\0', BUFFER_SIZE ); 134 | ret = recv( connfd, users[connfd].buf, BUFFER_SIZE-1, 0 ); 135 | printf( "get %d bytes of client data %s from %d\n", ret, users[connfd].buf, connfd ); 136 | if( ret < 0 ) 137 | { 138 | if( errno != EAGAIN ) 139 | { 140 | close( connfd ); 141 | users[fds[i].fd] = users[fds[user_counter].fd]; 142 | fds[i] = fds[user_counter]; 143 | i--; 144 | user_counter--; 145 | } 146 | } 147 | else if( ret == 0 ) 148 | { 149 | printf( "code should not come to here\n" ); 150 | } 151 | else 152 | { 153 | for( int j = 1; j <= user_counter; ++j ) 154 | { 155 | if( fds[j].fd == connfd ) 156 | { 157 | continue; 158 | } 159 | 160 | fds[j].events |= ~POLLIN; 161 | fds[j].events |= POLLOUT; 162 | users[fds[j].fd].write_buf = users[connfd].buf; 163 | } 164 | } 165 | } 166 | else if( fds[i].revents & POLLOUT ) 167 | { 168 | int connfd = fds[i].fd; 169 | if( ! users[connfd].write_buf ) 170 | { 171 | continue; 172 | } 173 | ret = send( connfd, users[connfd].write_buf, strlen( users[connfd].write_buf ), 0 ); 174 | users[connfd].write_buf = NULL; 175 | fds[i].events |= ~POLLOUT; 176 | fds[i].events |= POLLIN; 177 | } 178 | } 179 | } 180 | 181 | delete [] users; 182 | close( listenfd ); 183 | return 0; 184 | } 185 | -------------------------------------------------------------------------------- /mytalk_server_version1.cpp: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 1 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #define USER_LIMIT 5 16 | #define BUFFER_SIZE 64 17 | #define FD_LIMIT 65535 18 | 19 | struct client_data 20 | { 21 | sockaddr_in address; 22 | char* write_buf; 23 | char buf[ BUFFER_SIZE ]; 24 | }; 25 | 26 | int setnonblocking( int fd ) 27 | { 28 | int old_option = fcntl( fd, F_GETFL ); 29 | int new_option = old_option | O_NONBLOCK; 30 | fcntl( fd, F_SETFL, new_option ); 31 | return old_option; 32 | } 33 | 34 | int main( int argc, char* argv[] ) 35 | { 36 | if( argc <= 2 ) 37 | { 38 | printf( "usage: %s ip_address port_number\n", basename( argv[0] ) ); 39 | return 1; 40 | } 41 | const char* ip = argv[1]; 42 | int port = atoi( argv[2] ); 43 | 44 | int ret = 0; 45 | struct sockaddr_in address; 46 | bzero( &address, sizeof( address ) ); 47 | address.sin_family = AF_INET; 48 | inet_pton( AF_INET, ip, &address.sin_addr ); 49 | address.sin_port = htons( port ); 50 | 51 | int listenfd = socket( PF_INET, SOCK_STREAM, 0 ); 52 | assert( listenfd >= 0 ); 53 | 54 | ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) ); 55 | assert( ret != -1 ); 56 | 57 | ret = listen( listenfd, 5 ); 58 | assert( ret != -1 ); 59 | 60 | client_data* users = new client_data[FD_LIMIT]; 61 | pollfd fds[USER_LIMIT+1]; 62 | int user_counter = 0; 63 | for( int i = 1; i <= USER_LIMIT; ++i ) 64 | { 65 | fds[i].fd = -1; 66 | fds[i].events = 0; 67 | } 68 | fds[0].fd = listenfd; 69 | fds[0].events = POLLIN | POLLERR; 70 | fds[0].revents = 0; 71 | 72 | while( 1 ) 73 | { 74 | ret = poll( fds, user_counter+1, -1 ); 75 | if ( ret < 0 ) 76 | { 77 | printf( "poll failure\n" ); 78 | break; 79 | } 80 | 81 | for( int i = 0; i < user_counter+1; ++i ) 82 | { 83 | if( ( fds[i].fd == listenfd ) && ( fds[i].revents & POLLIN ) ) 84 | { 85 | struct sockaddr_in client_address; 86 | socklen_t client_addrlength = sizeof( client_address ); 87 | int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength ); 88 | if ( connfd < 0 ) 89 | { 90 | printf( "errno is: %d\n", errno ); 91 | continue; 92 | } 93 | if( user_counter >= USER_LIMIT ) 94 | { 95 | const char* info = "too many users\n"; 96 | printf( "%s", info ); 97 | send( connfd, info, strlen( info ), 0 ); 98 | close( connfd ); 99 | continue; 100 | } 101 | user_counter++; 102 | users[connfd].address = client_address; 103 | setnonblocking( connfd ); 104 | fds[user_counter].fd = connfd; 105 | fds[user_counter].events = POLLIN | POLLRDHUP | POLLERR; 106 | fds[user_counter].revents = 0; 107 | printf( "comes a new user, now have %d users\n", user_counter ); 108 | } 109 | else if( fds[i].revents & POLLERR ) 110 | { 111 | printf( "get an error from %d\n", fds[i].fd ); 112 | char errors[ 100 ]; 113 | memset( errors, '\0', 100 ); 114 | socklen_t length = sizeof( errors ); 115 | if( getsockopt( fds[i].fd, SOL_SOCKET, SO_ERROR, &errors, &length ) < 0 ) 116 | { 117 | printf( "get socket option failed\n" ); 118 | } 119 | continue; 120 | } 121 | else if( fds[i].revents & POLLRDHUP ) 122 | { 123 | users[fds[i].fd] = users[fds[user_counter].fd]; 124 | close( fds[i].fd ); 125 | fds[i] = fds[user_counter]; 126 | i--; 127 | user_counter--; 128 | printf( "a client left\n" ); 129 | } 130 | else if( fds[i].revents & POLLIN ) 131 | { 132 | int connfd = fds[i].fd; 133 | memset( users[connfd].buf, '\0', BUFFER_SIZE ); 134 | ret = recv( connfd, users[connfd].buf, BUFFER_SIZE-1, 0 ); 135 | printf( "get %d bytes of client data %s from %d\n", ret, users[connfd].buf, connfd ); 136 | if( ret < 0 ) 137 | { 138 | if( errno != EAGAIN ) 139 | { 140 | close( connfd ); 141 | users[fds[i].fd] = users[fds[user_counter].fd]; 142 | fds[i] = fds[user_counter]; 143 | i--; 144 | user_counter--; 145 | } 146 | } 147 | else if( ret == 0 ) 148 | { 149 | printf( "code should not come to here\n" ); 150 | } 151 | else 152 | { 153 | for( int j = 1; j <= user_counter; ++j ) 154 | { 155 | if( fds[j].fd == connfd ) 156 | { 157 | continue; 158 | } 159 | 160 | fds[j].events |= ~POLLIN; 161 | fds[j].events |= POLLOUT; 162 | users[fds[j].fd].write_buf = users[connfd].buf; 163 | } 164 | } 165 | } 166 | else if( fds[i].revents & POLLOUT ) 167 | { 168 | int connfd = fds[i].fd; 169 | if( ! users[connfd].write_buf ) 170 | { 171 | continue; 172 | } 173 | ret = send( connfd, users[connfd].write_buf, strlen( users[connfd].write_buf ), 0 ); 174 | users[connfd].write_buf = NULL; 175 | fds[i].events |= ~POLLOUT; 176 | fds[i].events |= POLLIN; 177 | } 178 | } 179 | } 180 | 181 | delete [] users; 182 | close( listenfd ); 183 | return 0; 184 | } 185 | -------------------------------------------------------------------------------- /mytalk_server_version2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #define USER_LIMIT 5 19 | #define BUFFER_SIZE 1024 20 | #define FD_LIMIT 65535 21 | #define MAX_EVENT_NUMBER 1024 22 | #define PROCESS_LIMIT 65536 23 | 24 | struct client_data 25 | { 26 | sockaddr_in address; 27 | int connfd; 28 | pid_t pid; 29 | int pipefd[2]; 30 | }; 31 | 32 | static const char* shm_name = "/my_shm"; 33 | int sig_pipefd[2]; 34 | int epollfd; 35 | int listenfd; 36 | int shmfd; 37 | char* share_mem = 0; 38 | client_data* users = 0; 39 | int* sub_process = 0; 40 | int user_count = 0; 41 | bool stop_child = false; 42 | 43 | int setnonblocking( int fd ) 44 | { 45 | int old_option = fcntl( fd, F_GETFL ); 46 | int new_option = old_option | O_NONBLOCK; 47 | fcntl( fd, F_SETFL, new_option ); 48 | return old_option; 49 | } 50 | 51 | void addfd( int epollfd, int fd ) 52 | { 53 | epoll_event event; 54 | event.data.fd = fd; 55 | event.events = EPOLLIN | EPOLLET; 56 | epoll_ctl( epollfd, EPOLL_CTL_ADD, fd, &event ); 57 | setnonblocking( fd ); 58 | } 59 | 60 | void sig_handler( int sig ) 61 | { 62 | int save_errno = errno; 63 | int msg = sig; 64 | send( sig_pipefd[1], ( char* )&msg, 1, 0 ); 65 | errno = save_errno; 66 | } 67 | 68 | void addsig( int sig, void(*handler)(int), bool restart = true ) 69 | { 70 | struct sigaction sa; 71 | memset( &sa, '\0', sizeof( sa ) ); 72 | sa.sa_handler = handler; 73 | if( restart ) 74 | { 75 | sa.sa_flags |= SA_RESTART; 76 | } 77 | sigfillset( &sa.sa_mask ); 78 | assert( sigaction( sig, &sa, NULL ) != -1 ); 79 | } 80 | 81 | void del_resource() 82 | { 83 | close( sig_pipefd[0] ); 84 | close( sig_pipefd[1] ); 85 | close( listenfd ); 86 | close( epollfd ); 87 | shm_unlink( shm_name ); 88 | delete [] users; 89 | delete [] sub_process; 90 | } 91 | 92 | void child_term_handler( int sig ) 93 | { 94 | stop_child = true; 95 | } 96 | 97 | int run_child( int idx, client_data* users, char* share_mem ) 98 | { 99 | epoll_event events[ MAX_EVENT_NUMBER ]; 100 | int child_epollfd = epoll_create( 5 ); 101 | assert( child_epollfd != -1 ); 102 | int connfd = users[idx].connfd; 103 | addfd( child_epollfd, connfd ); 104 | int pipefd = users[idx].pipefd[1]; 105 | addfd( child_epollfd, pipefd ); 106 | int ret; 107 | addsig( SIGTERM, child_term_handler, false ); 108 | 109 | while( !stop_child ) 110 | { 111 | int number = epoll_wait( child_epollfd, events, MAX_EVENT_NUMBER, -1 ); 112 | if ( ( number < 0 ) && ( errno != EINTR ) ) 113 | { 114 | printf( "epoll failure\n" ); 115 | break; 116 | } 117 | 118 | for ( int i = 0; i < number; i++ ) 119 | { 120 | int sockfd = events[i].data.fd; 121 | if( ( sockfd == connfd ) && ( events[i].events & EPOLLIN ) ) 122 | { 123 | memset( share_mem + idx*BUFFER_SIZE, '\0', BUFFER_SIZE ); 124 | ret = recv( connfd, share_mem + idx*BUFFER_SIZE, BUFFER_SIZE-1, 0 ); 125 | if( ret < 0 ) 126 | { 127 | if( errno != EAGAIN ) 128 | { 129 | stop_child = true; 130 | } 131 | } 132 | else if( ret == 0 ) 133 | { 134 | stop_child = true; 135 | } 136 | else 137 | { 138 | send( pipefd, ( char* )&idx, sizeof( idx ), 0 ); 139 | } 140 | } 141 | else if( ( sockfd == pipefd ) && ( events[i].events & EPOLLIN ) ) 142 | { 143 | int client = 0; 144 | ret = recv( sockfd, ( char* )&client, sizeof( client ), 0 ); 145 | if( ret < 0 ) 146 | { 147 | if( errno != EAGAIN ) 148 | { 149 | stop_child = true; 150 | } 151 | } 152 | else if( ret == 0 ) 153 | { 154 | stop_child = true; 155 | } 156 | else 157 | { 158 | send( connfd, share_mem + client * BUFFER_SIZE, BUFFER_SIZE, 0 ); 159 | } 160 | } 161 | else 162 | { 163 | continue; 164 | } 165 | } 166 | } 167 | 168 | close( connfd ); 169 | close( pipefd ); 170 | close( child_epollfd ); 171 | return 0; 172 | } 173 | 174 | int main( int argc, char* argv[] ) 175 | { 176 | if( argc <= 2 ) 177 | { 178 | printf( "usage: %s ip_address port_number\n", basename( argv[0] ) ); 179 | return 1; 180 | } 181 | const char* ip = argv[1]; 182 | int port = atoi( argv[2] ); 183 | 184 | int ret = 0; 185 | struct sockaddr_in address; 186 | bzero( &address, sizeof( address ) ); 187 | address.sin_family = AF_INET; 188 | inet_pton( AF_INET, ip, &address.sin_addr ); 189 | address.sin_port = htons( port ); 190 | 191 | listenfd = socket( PF_INET, SOCK_STREAM, 0 ); 192 | assert( listenfd >= 0 ); 193 | 194 | ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) ); 195 | assert( ret != -1 ); 196 | 197 | ret = listen( listenfd, 5 ); 198 | assert( ret != -1 ); 199 | 200 | user_count = 0; 201 | users = new client_data [ USER_LIMIT+1 ]; 202 | sub_process = new int [ PROCESS_LIMIT ]; 203 | for( int i = 0; i < PROCESS_LIMIT; ++i ) 204 | { 205 | sub_process[i] = -1; 206 | } 207 | 208 | epoll_event events[ MAX_EVENT_NUMBER ]; 209 | epollfd = epoll_create( 5 ); 210 | assert( epollfd != -1 ); 211 | addfd( epollfd, listenfd ); 212 | 213 | ret = socketpair( PF_UNIX, SOCK_STREAM, 0, sig_pipefd ); 214 | assert( ret != -1 ); 215 | setnonblocking( sig_pipefd[1] ); 216 | addfd( epollfd, sig_pipefd[0] ); 217 | 218 | addsig( SIGCHLD, sig_handler ); 219 | addsig( SIGTERM, sig_handler ); 220 | addsig( SIGINT, sig_handler ); 221 | addsig( SIGPIPE, SIG_IGN ); 222 | bool stop_server = false; 223 | bool terminate = false; 224 | 225 | shmfd = shm_open( shm_name, O_CREAT | O_RDWR, 0666 ); 226 | assert( shmfd != -1 ); 227 | ret = ftruncate( shmfd, USER_LIMIT * BUFFER_SIZE ); 228 | assert( ret != -1 ); 229 | 230 | share_mem = (char*)mmap( NULL, USER_LIMIT * BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0 ); 231 | assert( share_mem != MAP_FAILED ); 232 | close( shmfd ); 233 | 234 | while( !stop_server ) 235 | { 236 | int number = epoll_wait( epollfd, events, MAX_EVENT_NUMBER, -1 ); 237 | if ( ( number < 0 ) && ( errno != EINTR ) ) 238 | { 239 | printf( "epoll failure\n" ); 240 | break; 241 | } 242 | 243 | for ( int i = 0; i < number; i++ ) 244 | { 245 | int sockfd = events[i].data.fd; 246 | if( sockfd == listenfd ) 247 | { 248 | struct sockaddr_in client_address; 249 | socklen_t client_addrlength = sizeof( client_address ); 250 | int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength ); 251 | if ( connfd < 0 ) 252 | { 253 | printf( "errno is: %d\n", errno ); 254 | continue; 255 | } 256 | if( user_count >= USER_LIMIT ) 257 | { 258 | const char* info = "too many users\n"; 259 | printf( "%s", info ); 260 | send( connfd, info, strlen( info ), 0 ); 261 | close( connfd ); 262 | continue; 263 | } 264 | users[user_count].address = client_address; 265 | users[user_count].connfd = connfd; 266 | ret = socketpair( PF_UNIX, SOCK_STREAM, 0, users[user_count].pipefd ); 267 | assert( ret != -1 ); 268 | pid_t pid = fork(); 269 | if( pid < 0 ) 270 | { 271 | close( connfd ); 272 | continue; 273 | } 274 | else if( pid == 0 ) 275 | { 276 | close( epollfd ); 277 | close( listenfd ); 278 | close( users[user_count].pipefd[0] ); 279 | close( sig_pipefd[0] ); 280 | close( sig_pipefd[1] ); 281 | run_child( user_count, users, share_mem ); 282 | munmap( (void*)share_mem, USER_LIMIT * BUFFER_SIZE ); 283 | exit( 0 ); 284 | } 285 | else 286 | { 287 | close( connfd ); 288 | close( users[user_count].pipefd[1] ); 289 | addfd( epollfd, users[user_count].pipefd[0] ); 290 | users[user_count].pid = pid; 291 | sub_process[pid] = user_count; 292 | user_count++; 293 | } 294 | } 295 | else if( ( sockfd == sig_pipefd[0] ) && ( events[i].events & EPOLLIN ) ) 296 | { 297 | int sig; 298 | char signals[1024]; 299 | ret = recv( sig_pipefd[0], signals, sizeof( signals ), 0 ); 300 | if( ret == -1 ) 301 | { 302 | continue; 303 | } 304 | else if( ret == 0 ) 305 | { 306 | continue; 307 | } 308 | else 309 | { 310 | for( int i = 0; i < ret; ++i ) 311 | { 312 | switch( signals[i] ) 313 | { 314 | case SIGCHLD: 315 | { 316 | pid_t pid; 317 | int stat; 318 | while ( ( pid = waitpid( -1, &stat, WNOHANG ) ) > 0 ) 319 | { 320 | int del_user = sub_process[pid]; 321 | sub_process[pid] = -1; 322 | if( ( del_user < 0 ) || ( del_user > USER_LIMIT ) ) 323 | { 324 | printf( "the deleted user was not change\n" ); 325 | continue; 326 | } 327 | epoll_ctl( epollfd, EPOLL_CTL_DEL, users[del_user].pipefd[0], 0 ); 328 | close( users[del_user].pipefd[0] ); 329 | users[del_user] = users[--user_count]; 330 | sub_process[users[del_user].pid] = del_user; 331 | printf( "child %d exit, now we have %d users\n", del_user, user_count ); 332 | } 333 | if( terminate && user_count == 0 ) 334 | { 335 | stop_server = true; 336 | } 337 | break; 338 | } 339 | case SIGTERM: 340 | case SIGINT: 341 | { 342 | printf( "kill all the clild now\n" ); 343 | //addsig( SIGTERM, SIG_IGN ); 344 | //addsig( SIGINT, SIG_IGN ); 345 | if( user_count == 0 ) 346 | { 347 | stop_server = true; 348 | break; 349 | } 350 | for( int i = 0; i < user_count; ++i ) 351 | { 352 | int pid = users[i].pid; 353 | kill( pid, SIGTERM ); 354 | } 355 | terminate = true; 356 | break; 357 | } 358 | default: 359 | { 360 | break; 361 | } 362 | } 363 | } 364 | } 365 | } 366 | else if( events[i].events & EPOLLIN ) 367 | { 368 | int child = 0; 369 | ret = recv( sockfd, ( char* )&child, sizeof( child ), 0 ); 370 | printf( "read data from child accross pipe\n" ); 371 | if( ret == -1 ) 372 | { 373 | continue; 374 | } 375 | else if( ret == 0 ) 376 | { 377 | continue; 378 | } 379 | else 380 | { 381 | for( int j = 0; j < user_count; ++j ) 382 | { 383 | if( users[j].pipefd[0] != sockfd ) 384 | { 385 | printf( "send data to child accross pipe\n" ); 386 | send( users[j].pipefd[0], ( char* )&child, sizeof( child ), 0 ); 387 | } 388 | } 389 | } 390 | } 391 | } 392 | } 393 | 394 | del_resource(); 395 | return 0; 396 | } 397 | -------------------------------------------------------------------------------- /unblockconnect.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #define BUFFER_SIZE 1023 16 | 17 | int setnonblocking( int fd ) 18 | { 19 | int old_option = fcntl( fd, F_GETFL ); 20 | int new_option = old_option | O_NONBLOCK; 21 | fcntl( fd, F_SETFL, new_option ); 22 | return old_option; 23 | } 24 | 25 | int unblock_connect( const char* ip, int port, int time ) 26 | { 27 | int ret = 0; 28 | struct sockaddr_in address; 29 | bzero( &address, sizeof( address ) ); 30 | address.sin_family = AF_INET; 31 | inet_pton( AF_INET, ip, &address.sin_addr ); 32 | address.sin_port = htons( port ); 33 | 34 | int sockfd = socket( PF_INET, SOCK_STREAM, 0 ); 35 | int fdopt = setnonblocking( sockfd ); 36 | ret = connect( sockfd, ( struct sockaddr* )&address, sizeof( address ) ); 37 | if ( ret == 0 ) 38 | { 39 | printf( "connect with server immediately\n" ); 40 | fcntl( sockfd, F_SETFL, fdopt ); 41 | return sockfd; 42 | } 43 | else if ( errno != EINPROGRESS ) 44 | { 45 | printf( "unblock connect not support\n" ); 46 | return -1; 47 | } 48 | 49 | fd_set readfds; 50 | fd_set writefds; 51 | struct timeval timeout; 52 | 53 | FD_ZERO( &readfds ); 54 | FD_SET( sockfd, &writefds ); 55 | 56 | timeout.tv_sec = time; 57 | timeout.tv_usec = 0; 58 | 59 | ret = select( sockfd + 1, NULL, &writefds, NULL, &timeout ); 60 | if ( ret <= 0 ) 61 | { 62 | printf( "connection time out\n" ); 63 | close( sockfd ); 64 | return -1; 65 | } 66 | 67 | if ( ! FD_ISSET( sockfd, &writefds ) ) 68 | { 69 | printf( "no events on sockfd found\n" ); 70 | close( sockfd ); 71 | return -1; 72 | } 73 | 74 | int error = 0; 75 | socklen_t length = sizeof( error ); 76 | if( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &length ) < 0 ) 77 | { 78 | printf( "get socket option failed\n" ); 79 | close( sockfd ); 80 | return -1; 81 | } 82 | 83 | if( error != 0 ) 84 | { 85 | printf( "connection failed after select with the error: %d \n", error ); 86 | close( sockfd ); 87 | return -1; 88 | } 89 | 90 | printf( "connection ready after select with the socket: %d \n", sockfd ); 91 | fcntl( sockfd, F_SETFL, fdopt ); 92 | return sockfd; 93 | } 94 | 95 | int main( int argc, char* argv[] ) 96 | { 97 | if( argc <= 2 ) 98 | { 99 | printf( "usage: %s ip_address port_number\n", basename( argv[0] ) ); 100 | return 1; 101 | } 102 | const char* ip = argv[1]; 103 | int port = atoi( argv[2] ); 104 | 105 | int sockfd = unblock_connect( ip, port, 10 ); 106 | if ( sockfd < 0 ) 107 | { 108 | return 1; 109 | } 110 | shutdown( sockfd, SHUT_WR ); 111 | sleep( 200 ); 112 | printf( "send data out\n" ); 113 | send( sockfd, "abc", 3, 0 ); 114 | //sleep( 600 ); 115 | return 0; 116 | } 117 | --------------------------------------------------------------------------------