Socket编程实践 -- Select I/O复用

来源:互联网 发布:java工作流workflow 编辑:程序博客网 时间:2024/06/13 04:54

原文地址:http://blog.csdn.net/zjf280441589/article/details/41778347

Select函数

Man-Page

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* According to POSIX.1-2001 */  
  2. #include <sys/select.h>  
  3.   
  4. /* According to earlier standards */  
  5. #include <sys/time.h>  
  6. #include <sys/types.h>  
  7. #include <unistd.h>  
  8.   
  9. int select(int nfds, fd_set *readfds, fd_set *writefds,  
  10.            fd_set *exceptfds, struct timeval *timeout);  


Select使用说明:

    • 监视readfds来查看是否read的时候会被堵塞,注意,即便到了end-of-file,fd也是可读的。

    • 监视writefds看写的时候会不会被堵塞。

    • 监视exceptfd是否出现了异常。主要用来读取OOB数据,异常并不是指出错。

    • 注意当一个套接口出错时,它会变得既可读又可写。

    • 如果有了状态改变,会将其他fd清零,只有那些发生改变了的fd保持置位,以用来指示set中的哪一个改变了状态。

    • 参数n是所有set里所有fd里,具有最大值的那个fd的值加1

 

Select实现说明:

    调用select时通过参数告诉内核用户感兴趣的IO描述符

    关心的IO状态: 输入,输出或错误

    调用者等待时间

    返回之后内核告诉调用者多个描述符准备好了

    哪些描述符发生了变化

    调用返回后对准备好的描述符调用读写操作

    不关心的描述符集合传NULL

 

参数说明:

    1.nfds  is the highest-numbered file descriptor in any of the three sets,plus 1.

    2.fd_set[四个宏用来对fd_set进行操作]

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. FD_CLR(int fd, fd_set *set);  
  2. FD_ISSET(int fd, fd_set *set);  
  3. FD_SET(int fd, fd_set *set);  
  4. FD_ZERO(fd_set *set);  
 

    3.timeout[从调用开始到select返回前,会经历的最大等待时间]

    Timeval结构:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. struct timeval  
  2. {  
  3.     long    tv_sec;     /* seconds */  
  4.     long    tv_usec;    /* microseconds */  
  5. };  

说明:

    一些调用使用3个空的set, n为0, 一个非空的timeout来达到较为精确的sleep.

    Linux中, select函数改变了timeout值,用来指示还剩下的时间,但很多实现并不改timeout;因此为了较好的可移植性,timeout在循环中需要被重新赋初值。


Timeout取值:

    timeout== NULL

       无限等待,被信号打断时返回-1, errno 设置成 EINTR

   timeout->tv_sec == 0 && tvptr->tv_usec == 0

       不等待立即返回

   timeout->tv_sec != 0 || tvptr->tv_usec != 0

       等待特定时间长度, 超时返回0

 

返回值:

    On success, select() and pselect() return the number of  file  descriptors  contained  in  the  three  returned descriptor sets (that is, the total number of bits that are  set  in  readfds,  writefds,  exceptfds) which  may  be  zero if the timeout expires before anything interesting happens.  On error, -1 is returned, and errno is set appropriately; the sets  and  timeout  become  undefined, so do not rely on their contents after an error.

    如果成功,返回所有sets中描述符的个数;如果超时,返回0;如果出错,返回-1.

 

示例:(from man-page)

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <sys/time.h>  
  4. #include <sys/types.h>  
  5. #include <unistd.h>  
  6.   
  7. int main()  
  8. {  
  9.     fd_set rfds;  
  10.     struct timeval tv;  
  11.     int retval;  
  12.   
  13.     /* Watch stdin (fd 0) to see when it has input. */  
  14.     FD_ZERO(&rfds);  
  15.     FD_SET(0, &rfds);  
  16.   
  17.     /* Wait up to five seconds. */  
  18.     tv.tv_sec = 5;  
  19.     tv.tv_usec = 0;  
  20.   
  21.     retval = select(1, &rfds, NULL, NULL, &tv);  
  22.     /* Don't rely on the value of tv now! */  
  23.   
  24.     if (retval == -1)  
  25.         perror("select()");  
  26.     else if (retval)  
  27.     {  
  28.         if (FD_ISSET(0,&rfds))  
  29.         {  
  30.             char buf[BUFSIZ];  
  31.             cin >> buf;  
  32.             cout << "fd 0 is OK! and you input is: " << buf << endl;  
  33.         }  
  34.     }  
  35.     else  
  36.     {  
  37.         printf("No data within five seconds.\n");  
  38.     }  
  39.   
  40.     exit(EXIT_SUCCESS);  
  41. }  


Select实现原理

    fd_set是一个位向量, 每位表示一个描述符


[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. int FD_ISSET(int fd, fd_set *fdset);        //测试某个描述符是否在集合内  
  2. void FD_CLR(int fd, fd_set *fdset);     //从集合内把一个描述符移除  
  3. void FD_SET(int fd, fd_set *fdset);     //把一个描述符加入集合  
  4. void FD_ZERO(fd_set *fdset);                //清空描述符集合  

执行下列代码后:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. fd_set readset;  
  2. fd_set writeset;  
  3. FD_ZERO(&readset);  
  4. FD_ZERO(&writeset);  
  5.   
  6. FD_SET(0,&readset);  
  7. FD_SET(3,&readset);  
  8. FD_SET(1,&writeset);  
  9. FD_SET(2,&writeset);  
  10.   
  11. select(4,&readset,&writeset,NULL,NULL);  


Fd_set说明:

    • 可以把同一个描述符同时放取读和写集合

    • 当读和写者准备好时, 返回值的计数分别加1次

    • 普通文件的三种状态总是返回准备好的状态

    • 是否阻塞式IO不会影响select的结果

    • 如果一个描述符到了文件结尾,select返回的状态是准备好

    • 对一个准备好的描述符, 读出长度是0表示到达结尾

 

实践:用select优化客户端代码

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "commen.h"  
  2.   
  3. int main()  
  4. {  
  5.     int sockfd = mkATCPClient(9001,"127.0.0.1");  
  6.   
  7.     char sendBuf[BUFSIZ];  
  8.     char recvBuf[BUFSIZ];  
  9.   
  10.     while (true)  
  11.     {  
  12.         int fdCount = sockfd > STDIN_FILENO ? sockfd+1 : STDIN_FILENO+1;  
  13.         fd_set rdset;  
  14.         FD_ZERO(&rdset);  
  15.         FD_SET(sockfd,&rdset);  
  16.         FD_SET(STDIN_FILENO,&rdset);  
  17.   
  18.         int nReady = select(fdCount,&rdset,NULL,NULL,NULL);  
  19.         if (nReady == -1)  
  20.         {  
  21.             err_exit("select error");  
  22.         }  
  23.   
  24.         //server端有数据可读  
  25.         if (FD_ISSET(sockfd,&rdset))  
  26.         {  
  27.             //从socket中读取数据  
  28.             int readCount = read(sockfd,recvBuf,sizeof(recvBuf));  
  29.             if ( readCount == -1)  
  30.             {  
  31.                 err_exit("read socket error");  
  32.             }  
  33.             else if (readCount == 0)    //如果对端结束链接  
  34.             {  
  35.                 peerClosePrint();  
  36.             }  
  37.             fputs(recvBuf,stdout);  
  38.             memset(recvBuf,0,sizeof(recvBuf));  
  39.         }  
  40.   
  41.         //标准输入上有数据可读:从键盘读取数据 -> 发送至socket  
  42.         if (FD_ISSET(STDIN_FILENO,&rdset));  
  43.         {  
  44.             if(fgets(sendBuf,sizeof(sendBuf),stdin) != NULL)  
  45.             {  
  46.                 if (write(sockfd,sendBuf,strlen(sendBuf)) == -1)    //发送到socket上  
  47.                 {  
  48.                     err_exit("write error");  
  49.                 }  
  50.                 memset(sendBuf,0,sizeof(sendBuf));  
  51.             }  
  52.         }  
  53.     }  
  54.   
  55.     close(sockfd);  
  56.     return 0;  
  57. }  
  58. /**说明: 
  59.   Server端代码同前(echo server) 
  60. */  

-commen.h源代码

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #ifndef COMMEN_H_INCLUDED  
  2. #define COMMEN_H_INCLUDED  
  3.   
  4. #include <unistd.h>  
  5. #include <signal.h>  
  6. #include <errno.h>  
  7. #include <fcntl.h>  
  8. #include <sys/types.h>  
  9. #include <sys/wait.h>  
  10. #include <sys/stat.h>  
  11. #include <sys/ipc.h>  
  12. #include <sys/shm.h>  
  13. #include <sys/msg.h>  
  14. #include <sys/sem.h>  
  15. #include <sys/socket.h>  
  16.   
  17. #include <sys/select.h>  
  18.   
  19. #include <arpa/inet.h>  
  20. #include <sys/socket.h>  
  21. #include <netinet/in.h>  
  22.   
  23. #include <arpa/inet.h>  
  24. #include <string.h>  
  25. #include <stdio.h>  
  26. #include <stdlib.h>  
  27.   
  28. #include <iostream>  
  29. using namespace std;  
  30.   
  31. void err_exit(std::string str)  
  32. {  
  33.     perror(str.c_str());  
  34.     exit(EXIT_FAILURE);  
  35. }  
  36. void peerClosePrint(std::string str = "peer connect closed")  
  37. {  
  38.     cout << str << endl;  
  39.     _exit(0);  
  40. }  
  41.   
  42. //return a socket that have start listened.  
  43. int mkATCPServer(int serverPort, int backlog = SOMAXCONN)  
  44. {  
  45.     int sockfd = socket(AF_INET,SOCK_STREAM,0);  
  46.     if (sockfd == -1)  
  47.     {  
  48.         err_exit("socket error");  
  49.     }  
  50.   
  51.     //add address reused  
  52.     int on = 1;  
  53.     if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)) == -1)  
  54.     {  
  55.         err_exit("setsockopt SO_REUSEADDR error");  
  56.     }  
  57.   
  58.     //band a local address and port  
  59.     struct sockaddr_in serverAddr;  
  60.     serverAddr.sin_family = AF_INET;  
  61.     serverAddr.sin_port = htons(serverPort);  
  62.     serverAddr.sin_addr.s_addr = INADDR_ANY;    //band an any IP address  
  63.     if (bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr)) == -1)  
  64.     {  
  65.         err_exit("bind error");  
  66.     }  
  67.   
  68.     //start to listen.  
  69.     if (listen(sockfd,backlog) == -1)  
  70.     {  
  71.         err_exit("listen error");  
  72.     }  
  73.   
  74.     return sockfd;  
  75. }  
  76.   
  77. //return a socket that have connected to server.  
  78. int mkATCPClient(int serverPort, string serverIPAddr)  
  79. {  
  80.     //first. create a socket  
  81.     int sockfd = socket(AF_INET,SOCK_STREAM,0);  
  82.     if (sockfd == -1)  
  83.     {  
  84.         err_exit("socket error");  
  85.     }  
  86.   
  87.     //second. connect to a server  
  88.     struct sockaddr_in serverAddr;  
  89.     serverAddr.sin_family = AF_INET;  
  90.     serverAddr.sin_port = htons(serverPort);  
  91.     serverAddr.sin_addr.s_addr = inet_addr(serverIPAddr.c_str());  
  92.     if (connect(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr)) == -1)  
  93.     {  
  94.         err_exit("connect error");  
  95.     }  
  96.   
  97.     return sockfd;  
  98. }  
  99.   
  100. void onCatchSIGCHLD(int signalNumber)  
  101. {  
  102.     int ret = 0;  
  103.     while ((ret = waitpid(-1,NULL,WNOHANG) != -1))  
  104.         ;  
  105. }  
  106.   
  107. ssize_t readn(int fd,void *buf,size_t count)  
  108. {  
  109.     size_t nLeft = count;  
  110.     ssize_t nRead = 0;  
  111.   
  112.     char *ptr = static_cast<char *>(buf);  
  113.   
  114.     while (nLeft > 0)  
  115.     {  
  116.         if ((nRead = read(fd,ptr,nLeft)) < 0)  
  117.         {  
  118.             //一点东西都没读  
  119.             if (nLeft == count)  
  120.             {  
  121.                 return -1;  //error  
  122.             }  
  123.             else  
  124.             {  
  125.                 break;  //error, return amount read so far  
  126.             }  
  127.         }  
  128.         else if (nRead == 0)  
  129.         {  
  130.             break;  //EOF  
  131.         }  
  132.   
  133.         nLeft -= nRead;  
  134.         ptr += nRead;  
  135.     }  
  136.   
  137.     return count - nLeft;  
  138. }  
  139.   
  140. ssize_t writen(int fd, const void *buf, size_t count)  
  141. {  
  142.     size_t nLeft = count;  
  143.     ssize_t nWritten;  
  144.   
  145.     const char *ptr = static_cast<const char *>(buf);  
  146.   
  147.     while (nLeft > 0)  
  148.     {  
  149.         if ((nWritten = write(fd,ptr,nLeft)) < 0)  
  150.         {  
  151.             //一点东西都没写  
  152.             if (nLeft == count)  
  153.             {  
  154.                 return -1;  //error  
  155.             }  
  156.             else  
  157.             {  
  158.                 break;  //error, return amount write so far  
  159.             }  
  160.         }  
  161.         else if (nWritten == 0)  
  162.         {  
  163.             break;  //EOF  
  164.         }  
  165.   
  166.         nLeft -= nWritten;  
  167.         ptr += nWritten;  
  168.     }  
  169.   
  170.     return count - nWritten;  
  171. }  
  172.   
  173. //只是查看一下网络中的数据,并不是将之真正取走:MSG_PEEK  
  174. ssize_t recv_peek(int fd, void *buf, size_t count)  
  175. {  
  176.     int nRead = 0;  
  177.     //如果读取网络数据出错,则继续读取  
  178.     while ((nRead = recv(fd,buf,count,MSG_PEEK)) == -1);  
  179.     return nRead;  
  180. }  
  181.   
  182. ssize_t readline(int fd, void *buf, size_t maxline)  
  183. {  
  184.     char *pBuf = (char *)buf;  
  185.     int nLeft = maxline;  
  186.   
  187.     while (true)  
  188.     {  
  189.         //查看缓冲区中的数据,并不真正取走  
  190.         int nTestRead = recv_peek(fd,pBuf,nLeft);  
  191.   
  192.         //检测这次读来的数据中是否包含'\n';  
  193.         //如果有,则将之全部读取出来  
  194.         for (int i = 0; i < nTestRead; ++i)  
  195.         {  
  196.             if (pBuf[i] == '\n')  
  197.             {  
  198.                 //真正的从缓冲区中将数据取走  
  199.                 if (readn(fd,pBuf,i+1) != i+1)  
  200.                 {  
  201.                     err_exit("readn error");  
  202.                 }  
  203.                 else  
  204.                 {  
  205.                     return i + 1;  
  206.                 }  
  207.             }  
  208.         }  
  209.   
  210.         //如果这次读的缓冲区中没有'\n'  
  211.   
  212.         //如果读超了:读道德数目大于一行最大数,则做异常处理  
  213.         if (nTestRead > nLeft)  
  214.         {  
  215.             exit(EXIT_FAILURE);  
  216.         }  
  217.   
  218.         nLeft -= nTestRead; //若缓冲区没有'\n',则将剩余的数据读走  
  219.         if (readn(fd,pBuf,nTestRead) != nTestRead)  
  220.         {  
  221.             exit(EXIT_FAILURE);  
  222.         }  
  223.   
  224.         pBuf += nTestRead;  
  225.     }  
  226.   
  227.     return -1;  
  228. }  
  229.   
  230. #endif // COMMEN_H_INCLUDED 
0 0
原创粉丝点击