To thoroughly understand poll or understand the following code, please refer to the "Linux network programming--i/o multiplexing poll function"
Code:
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys /select.h> #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include < arpa/inet.h> #include <poll.h> #include <errno.h> #define OPEN_MAX 100int Main (int argc, char *argv[]) {// 1. Create a TCP listener socket int SOCKFD = socket (af_inet, sock_stream, 0);//2. Bind sockfdstruct sockaddr_in My_addr;bzero (&MY_ADDR, sizeof (MY_ADDR)); my_addr.sin_family = Af_inet;my_addr.sin_port = htons (8000); my_addr.sin_addr.s_addr = Htonl (inaddr_ Any), bind (SOCKFD, (struct sockaddr *) &my_addr, sizeof (MY_ADDR)),//3. Monitoring Listenlisten (SOCKFD, 10);//4. Poll corresponding parameters prepare the struct POLLFD client[open_max];int i = 0, maxi = 0;for (;i<open_max; i++) CLIENT[I].FD = -1;//Initialize the file descriptor in the poll structure FDCLIENT[0].FD = sockfd;//The descriptor to be monitored client[0].events = pollin;//normal or priority with data-readable//5. Data processing for connected clients while (1) {int ret = poll ( Client, Maxi+1,-1);//monitor the inclusion of all elements of the poll structure array//5.1 monitor SOCKFD (listening sockets) If there is a connection if (Client[0].revenTS & Pollin) = = Pollin) {struct sockaddr_in cli_addr;int clilen = sizeof (CLI_ADDR); int connfd = 0;//5.1.1 Extract guest from TCP completion connection The Client CONNFD = Accept (SOCKFD, (struct sockaddr *) &cli_addr, &clilen)//5.1.2 the extracted connfd into the poll struct array, For easy poll function monitoring for (i=1; i<open_max; i++) {if (CLIENT[I].FD < 0) {client[i].fd = Connfd;client[i].events = Pollin;break;}} 5.1.3 Maxi Update if (I > Maxi) maxi = i;//5.1.4 If there is no ready descriptor, continue to poll monitoring, otherwise continue to look down if (--ret <= 0) continue;} 5.2 Continue response Ready descriptor for (i=1; i<=maxi; i++) {if (CLIENT[I].FD < 0) continue;if (client[i].revents & (Pollin | POLLERR) {int len = 0;char buf[128] = "";//5.2.1 Accept client Data if (len = recv (client[i].fd, buf, sizeof (BUF), 0)) < 0) {if (errno = = econnreset)//tcp connection timeout, rst{close (CLIENT[I].FD); client[i].fd =-1;} Elseperror ("Read error:");} else if (len = = 0)//client close connection {close (CLIENT[I].FD); client[i].fd =-1;} else//normally receives the data sent to the server (CLIENT[I].FD, buf, Len, 0),//5.2.2 all the ready descriptors have been processed, exits the current for loop and continues poll monitoring if (--ret <= 0) break;}} return 0;}
Operation Result:
Source Download:
Linux Network Programming--tcp Concurrent Server (poll implementation)