The poll function is similar to the Select function. The following is a simple echo server
#include <iostream>using namespacestd; #include<poll.h>#include<limits.h>#defineOpen_max 64intMain () {intI, Maxi, LISTENFD, CONNFD, SOCKFD; intNready; ssize_t N; Socklen_t Clilen; structPOLLFD Client[open_max]; structsockaddr_in cliaddr, servaddr; LISTENFD= Socket (Af_inet, Sock_stream,0); Servaddr.sin_family=af_inet; Servaddr.sin_port= Htons (10002); Servaddr.sin_addr.s_addr= Inet_addr ("127.0.0.1"); if(Bind (LISTENFD, (sockaddr*) &servaddr,sizeof(SERVADDR)) == -1) {cout<<"bind error"<<Endl; return-1; } Listen (LISTENFD,5); client[0].FD =LISTENFD; client[0].events =Pollrdnorm; for(inti =1; i < Open_max; i++) {CLIENT[I].FD= -1; } Maxi=0; cout<<"startup sucess Port:"<< Servaddr.sin_port <<Endl; cout<<"Max Connect:"<< Open_max <<Endl; for(;;) {Nready= Poll (client, Maxi +1, -1); if(Nready = =-1) {cout<<"Poll Error"<<Endl; } if(client[0].revents & Pollrdnorm)//New Client Connection{Clilen=sizeof(CLIADDR); CONNFD= Accept (LISTENFD, (sockaddr*) &cliaddr, &Clilen); for(i =1; i < Open_max; i++) { if(Client[i].fd <0) {CLIENT[I].FD= CONNFD;//Save des Break; } } if(i = =Open_max) {cout<<"Too many clients"<<Endl; return-1; } client[i].events=Pollrdnorm; if(I >Maxi) {Maxi=i; } if(--nready <=0) { Continue; } } for(i =1; I <= Maxi; i++) { if((SOCKFD = CLIENT[I].FD) <0) { Continue; } if(Client[i].revents & (Pollrdnorm |Pollerr)) { Charbuffer[1024x768] = {0}; if(n = recv (sockfd, buffer,1024x768,0)) <0) { if(errno = =Econnreset) { //connection reset by clientClose (SOCKFD); CLIENT[I].FD= -1; } Else{cout<<"Read Error"<<Endl; } } Else if(n = =0) { //connect close by clientClose (SOCKFD); CLIENT[I].FD= -1; } Else{Send (SOCKFD, buffer,1024x768,0); } if(--nready <=0) { Break; } } } } return 0;}
UNIX Network Programming-poll model ECHO Server