title: Implementing poll() on a TCP server's read/write
body: <p>I need this server to be able to listen for and establish new connections with clients while simultaneously writing to existing connections.. ie. Asynchronous non-blocking i/o.  I've been told to use poll() but after spending an inordinate amount of time simply trying to grasp socket programming, I'm still unsure how implement the poll() function.</p>
  
  <pre><code>int sockfd; 
  
  int main(int argc, char *argv[])
  {
   int newsockfd, portno; 
   socklen_t clilen;  
   char buffer[256];       
   struct sockaddr_in serv_addr, cli_addr;  
   int n;             
  
   if (argc &lt; 2) {         
       fprintf(stderr,"ERROR, no port provided\n"); 
       exit(1);
   }
  
   sockfd = socket(AF_INET, SOCK_STREAM, 0);      
   if (sockfd &lt; 0)                    
      error("ERROR opening socket");          
  
   bzero((char *) &amp;serv_addr, sizeof(serv_addr));     
  
   portno = atoi(argv[1]);            
   serv_addr.sin_family = AF_INET;        
   serv_addr.sin_addr.s_addr = INADDR_ANY;    
   serv_addr.sin_port = htons(portno);    
  
   if (bind(sockfd, (struct sockaddr *) &amp;serv_addr, 
            sizeof(serv_addr)) &lt; 0) 
            error("ERROR on binding");        
   listen(sockfd,5);                  
  
   clilen = sizeof(cli_addr);     
  
   while(1){          
       newsockfd = accept(sockfd, 
                   (struct sockaddr *) &amp;cli_addr, 
                   &amp;clilen);              
       if (newsockfd &lt; 0)                 
            error("ERROR on accept");
  
       // READ READ READ READ READ READ READ READ READ READ READ READ READ READ READ READ 
       bzero(buffer,256);
       n = read(newsockfd,buffer,255);    
  
  
       if (n &lt; 0) error("ERROR reading from socket");
       printf("Here is the message: %s\n",buffer);
  
       // WRITE WRITE WRITE WRITE WRITE WRITE WRITE WRITE WRITE WRITE WRITE WRITE WRITE 
       n = write(newsockfd,"I got your message",18); 
       if (n &lt; 0) error("ERROR writing to socket");
       close(newsockfd);  
   }
  
   return 0; 
  </code></pre>
  
  <p>}</p>
  
  <p>My understanding is that I need to build something like this:</p>
  
  <pre><code>//  Set up array of file descriptors for polling
  struct pollfd ufds[2];
  ufds[0].fd = sockfd;    
  ufds[0].events = POLLIN; 
  
  ufds[1].fd = newsockfd;
  ufds[1].events = POLLOUT;
  </code></pre>
  
  <p>and use poll(ufds,2,2000); inside the loop to check whether sockfd or newsockfd have any activity, in which case I use the appropriate read or write.. If anybody could give me some guidance I'd be very appreciative. </p>