UNIX Network Programming-poll model ECHO Server

Source: Internet
Author: User
Tags connection reset

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.