Poll---Socket client/server-side programming

Source: Internet
Author: User
Tags htons

The poll function is similar to select, but the program interface is different. Poll function Any type of file descriptor.

Before writing a program with the poll function, let's take a look at the prototype of the poll function:

int poll (struct pollfd* fds,nfds_t nfds,int timeout);

Let's take a look at its parameters:

The first parameter is a pointer to the first element of an array of structures. Each array element is a POLLFD structure that specifies the criteria for testing a given descriptor FD. Unlike Select, poll constructs a set of descriptors for each condition (readability, writeable, and exception conditions) instead of constructing an array of POLLFD structures, each of which specifies a descriptor number and the conditions in which we are interested. The structure is as follows:

struct pollfd{

int FD;

Short events;

Short revents;

}

The number of elements in the array is specified by Nfds. The conditions to be tested are specified by the events member, so we tell the kernel what events we care about for each descriptor. The function returns the state of the descriptor in the corresponding Revents member, and the Revents member is set by the kernel to describe which events each descriptor has occurred.

The third parameter, like Select, has 3 different scenarios, meaning how long we are willing to wait.

When timeout is-1, it means to wait forever and wait. Returned when one of the specified descriptors is ready, or is snapped to a signal.

When timeout is 0 o'clock, we do not wait. Tests all descriptors and returns immediately. It can be said that this is a polling method, you can find the state of multiple descriptors without blocking the poll function.

When timeout is greater than 0 o'clock, we wait for timeout milliseconds. Returns immediately when one of the specified descriptors is ready, or timeout timeout. If the timeout expires without a descriptor ready, the return value is 0;


If we no longer care about a particular descriptor, then we can set the FD member of the POLLFD structure corresponding to it to a negative value. The poll function ignores the events member of such a POLLFD structure, returning the value of its revents member to 0.


Let's take a look at the specific code and use the poll function to implement a simple client/server-side model:

Server side:

#include  <stdio.h>    #include  <stdlib.h>    #include   <assert.h>    #include  <poll.h>    #include  <unistd.h>     #include  <netinet/in.h>    #include  <sys/types.h>     #include  <sys/socket.h>    #include  <arpa/inet.h>      #define  _BACKLOG_ 5   #define  _CLIENT_ 64     Static void usage (Const char* arg)   {      printf ( "Usage:%s [ip][port]", ARG);   }    static int start (Char *ip, Int port)   {      assert (IP);       Int sock=socket (af_inet,sock_stream,0);                                                                                                                                      if (sock<0)       {           perror ("socket");           Exit (1);      }      struct sockaddr_in  local;      local.sin_family=af_inet;      local.sin_port=htons (port); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOCAL.SIN_ADDR.S_ADDR=INET_ADDR (IP);         if (Bind (sock, (struct sockaddr*) &local,sizeof (local)) <0)        {          perror ("bind");           exit (2);      }         if (Listen (Sock,_backlog_) <0)       {           perror ("Listen");           exit (3);      }         Return sock;  }    int main (int argc,char *argv[])    {     &Nbsp;if (argc!=3)       {           usage (argv[0]);                                                                                                                                                         &nBsp;     exit (1);      }       int i,maxi;//client the maximum subscript       int port=atoi (argv[2]) of the array;       char *ip=argv[1];        int  Listenfd=start (Ip,port);      int done=0;       int new_sock=-1;      struct sockaddr_in client;       socklen_t len=sizeof (client);       struct  pollfd clientfds[_client_];        clientfds[0].fd=listenfd ;       clientfds[0].events=pollin;      int _ Timeout=5000;      for (i=1;i<_backlog_;++i)        {          clientfds[i].fd=-1;      }       maxi=0;     int ret;     while (1)      {         ret=poll (clientfds,maxi+1 , _timeout);          if (ret<0)           {             printf ( "poll error\n");              exit (1);           }          else if (ret==0)          {              perror ("Time out");               //exit (2);                                                                                                                                                               }          if (clientfDs[0].revents&pollin)          {              new_sock=accept (LISTENFD, (struct sockaddr*) &client, &len);                          printf ("get a connect...%d\n", New_sock);              for (i=1;i<_CLIENT_;++i)               {                  if (clientfds[i].fd<0)                   {                      clientfds[i]. Fd=new_sock;   //save descriptor                      break;                  }              }             if (I==_CLIENT _)              {                   close (New_sock);              }              clientfds[i].events=POLLIN;              if (I>maxi)               {                 maxi=i;              }          }                                                                                                                                                                              for (i=1;i<=maxi;++i)          {              if (clientfds[i].fd<0)               {                  continue;              }              if (Clientfds[i].revents&pollin)               {                  Char buf[1024];                 ssize_t _s= Read (clientfds[i].fd,buf,sizeof (BUF)-1);                  if (_s>0)                   {                      buf[_s]= ';                      printf ("Client:  %s ", buf);                  }                  else if (_s==0)                   {                      printf ("client quit...\n");                      close (CLIENTFDS[I].FD);                      clientfds[i]. fd=-1;                 }              }          }     }     return 0; }

Client side:

#include  <stdio.h>    #include  <stdlib.h>    #include   <assert.h>    #include  <poll.h>    #include  <unistd.h>     #include  <netinet/in.h>    #include  <sys/types.h>     #include  <sys/socket.h>    #include  <arpa/inet.h>     static void usage (Const char* arg)   {       printf ("Usage:%s [ip][port]", ARG);   }    int main (INT&NBSP;ARGC, Char *argv[])   {      if (argc!=3)        {          usage (argv[0]);           exit (1);      }         iNt port=atoi (argv[2]);      char *ip=argv[1];         int sock=socket (af_inet,sock_stream,0);       if ( sock<0)       {           Perror ("socket");           exit (2);       }                                                                                                                                                                                     struct sockaddr_in remote;       remote.sin_family=af_inet;      remote.sin_port=htons (port);  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;REMOTE.SIN_ADDR.S_ADDR=INET_ADDR (IP);         int ret=connect (sock, (struct sockaddr*) &remote,sizeof (remote));                                                                                                                                                                                      char buf[1024];      while (1)       {           printf ("please enter: ");           fflush (stdout);           ssize_t _s= Read (0,buf,sizeof (BUF)-1);           buf[_s]= ';           write (sock,buf,sizeof (BUF)-1);       }      return 0;  }

The result of the above code is as follows:

650) this.width=650; "title=" tn]{) 1y5sf ' AC6PQVR@LENQ.png "src=" http://s2.51cto.com/wyfs02/M02/82/00/ Wkiom1dg63sjuvvfaacdwk9_r64930.png-wh_500x0-wm_3-wmp_4-s_4260840385.png "alt=" wKiom1dG63SjuVVFAACDwk9_ R64930.png-wh_50 "/>

From the above results we see that the data sent by the client is received by the Service Short board, the server will print a "time out:success" message after we set the timeout timeout, so the whole program is written.










Poll---Socket client/server-side programming

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.