/* Echo server implemented by poll. author: thinkmay */# include <stdio. h> # include <stdlib. h> # include <string. h> # include <unistd. h> # include <poll. h> # include <sys/socket. h> # include <netinet/in. h> # include <ARPA/inet. h> # include <sys/types. h> # include <errno. h> # define open_max 512 # define bufsize 1024int main (INT argc, char ** argv) {// determine whether the running format is correct if (argc! = 2) {printf ("Usage :. /poll <port> "); exit (-1);} int listensock, connsock; struct sockaddr_in servaddr; struct pollfd FDS [open_max]; // defines the pollfd struct int I, count = 0, ready, Reval; char readbuf [bufsize]; // first, the fd values of the pollfd structure array are-1 for (I = 0; I <open_max; I ++) {FDS [I]. FD =-1; // value FD to-1 in a loop .} // create a TCP socket If (listensock = socket (af_inet, sock_stream, 0) <0) {perror ("socket error"); exit (-1 );} memset (& servaddr, 0, sizeof (servaddr); // clear the socket address variable 0 servaddr. sin_family = af_inet; servaddr. sin_family = htonl (inaddr_any); servaddr. sin_port = htons (atoi (argv [1]); // bind the socket and socket address variable if (BIND (listensock, (struct sockaddr *) & servaddr, sizeof (servaddr) <0) {perror ("BIND error"); exit (-1);} // listen to socket If (Listen (listensock, 5) <0) {perror ("Listen error"); exit (-1) ;}// add 0 and listensock to the pollfd struct FDS [0]. FD = 0; // Add the standard input to FDS [0]. events = Pollin; // specify the trigger event status count ++; FDS [1]. FD = listensock; FDS [1]. events = Pollin; count ++; For (;) {memset (readbuf, 0, bufsize); ready = poll (FDS, Count, 0 ); // define poll preparation for (I = 0; I <count; I ++) {// revents returns the trigger status if (FDS [I]. revents & Pollin) // determines whether Pollin triggers {If (FDS [I]. FD = 0) {fgets (readbuf, bufsize, stdin); printf ("read Buf: % s \ n", readbuf);} else if (FDS [I]. FD = listensock) {connsock = accept (listensock, null, null); printf ("client connect \ n"); FDS [count]. FD = connsock; FDS [count]. events = Pollin; count ++;} else {reval = Recv (FDS [I]. FD, readbuf, bufsize, 0); printf ("Recv Buf: % s \ n", readbuf); send (FDS [I]. FD, readbuf, Reval, 0) ;}}} return 0 ;}