http://blog.chinaunix.net/space.php?uid=25944391&do=blog&id=2854240

本片文章,在上一篇:linux网络编程:用C语言实现的聊天程序(同步通信) 的基础上,增加了IO复用的功能,实现了聊天程序的异步通讯!

1、使用IO复用可以在等待的时候加入了超时的时间,如果等待的时间没有达到超时时间,那么该情况与阻塞的情况一致。而当超时的时间到达时,仍没有数据接收到,系统回返回0,不再等待。select函数就实现了这个功能。

2、select函数原型
int select (int maxfdp1, fd_set *readset, fd_set *writeset,   fd_set *exceptset, const struct timeval * timeout);
a)返回值
>0:就绪的描述符  
-1:出错  
0 :超时     
struct timeval{  
long tv_sec; // seconds  
long tv_usec; // microseconds
}
b)具体解释select的参数
int maxfdp是一个整数值,是指集合中所有文件描述符的范围,即所有文件描述符的最大值加1;
fd_set*readfds 文件描述符集合内,是否有数据可读;
fd_set*writefds  文件描述符集合内,是否有数据可写;
fd_set *errorfds  文件描述符集合内,是否有文件发生错误;
struct timeval *timeout是select的超时时间,它可以使select处于三种状态,第一,若将NULL以形参传入,就是将select置于阻塞状态;第二, 若将时间值设为0秒0毫秒,就变成一个纯粹的非阻塞函数,不管文件描述符是否有变化,都立刻返回继续执行,文件无变化返回0,有变化返回一个正值;第 三,timeout的值大于0,这就是等待的超时时间,即select在timeout时间内阻塞。
c)4个宏可以操作文件描述符的集合
void FD_ZERO (fd_set *fdset); // 初始化文件描述集合  
void FD_SET (int fd, fd_set *fdset); // 将描述符加入到集合中  
void FD_CLR (int fd, fd_set *fdset); // 将描述符中集合中删除  
int FD_ISSET (int fd, fd_set *fdset); // 检查描述符集合中指定的文件描述符是否可读写

3、客户端源代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <sys/socket.h>
  6. #include <arpa/inet.h>
  7. #include <netinet/in.h>
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10. #include <sys/time.h>

  11. #define BUFLEN 1024

  12. int main(int argc, char **argv)
  13. {
  14.     int sockfd;
  15.     struct sockaddr_in s_addr;
  16.     socklen_t len;
  17.     unsigned int port;
  18.     char buf[BUFLEN];
  19.     fd_set rfds;
  20.     struct timeval tv;
  21.     int retval, maxfd;    
  22.     
  23.     /*建立socket*/
  24.     if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
  25.         perror("socket");
  26.         exit(errno);
  27.     }else
  28.         printf("socket create success!\n");

  29.     /*设置服务器端口*/    
  30.     if(argv[2])
  31.         port = atoi(argv[2]);
  32.     else
  33.         port = 4567;
  34.     /*设置服务器ip*/
  35.     bzero(&s_addr, sizeof(s_addr));
  36.     s_addr.sin_family = AF_INET;
  37.     s_addr.sin_port = htons(port);
  38.     if (inet_aton(argv[1], (struct in_addr *)&s_addr.sin_addr.s_addr) == 0) {
  39.         perror(argv[1]);
  40.         exit(errno);
  41.     }
  42.     /*开始连接服务器*/    
  43.     if(connect(sockfd,(struct sockaddr*)&s_addr,sizeof(struct sockaddr)) == -1){
  44.         perror("connect");
  45.         exit(errno);
  46.     }else
  47.         printf("conncet success!\n");
  48.     
  49.     while(1){
  50.         /*把可读文件描述符的集合清空*/
  51.         FD_ZERO(&rfds);
  52.         /*把标准输入的文件描述符加入到集合中*/
  53.         FD_SET(0, &rfds);
  54.         maxfd = 0;
  55.         /*把当前连接的文件描述符加入到集合中*/
  56.         FD_SET(sockfd, &rfds);
  57.         /*找出文件描述符集合中最大的文件描述符*/    
  58.         if(maxfd < sockfd)
  59.             maxfd = sockfd;
  60.         /*设置超时时间*/
  61.         tv.tv_sec = 5;
  62.         tv.tv_usec = 0;
  63.         /*等待聊天*/
  64.         retval = select(maxfd+1, &rfds, NULL, NULL, &tv);
  65.         if(retval == -1){
  66.             printf("select出错,客户端程序退出\n");
  67.             break;
  68.         }else if(retval == 0){
  69.             printf("客户端没有任何输入信息,并且服务器也没有信息到来,waiting...\n");
  70.             continue;
  71.         }else{
  72.             /*服务器发来了消息*/
  73.             if(FD_ISSET(sockfd,&rfds)){
  74.                 /******接收消息*******/
  75.                 bzero(buf,BUFLEN);
  76.                 len = recv(sockfd,buf,BUFLEN,0);
  77.                 if(len > 0)
  78.                     printf("服务器发来的消息是:%s,共有字节数是: %d\n",buf,len);
  79.                 else{
  80.                     if(len < 0 )
  81.                         printf("接受消息失败!\n");
  82.                     else
  83.                         printf("服务器退出了,聊天终止!\n");
  84.                 break;    
  85.                 }
  86.             }
  87.             /*用户输入信息了,开始处理信息并发送*/
  88.             if(FD_ISSET(0, &rfds)){
  89.             _retry:    
  90.                 /******发送消息*******/    
  91.                 bzero(buf,BUFLEN);
  92.                 /*fgets函数:从流中读取BUFLEN-1个字符*/
  93.                 fgets(buf,BUFLEN,stdin);
  94.                 /*打印发送的消息*/
  95.                 //fputs(buf,stdout);
  96.                 if(!strncasecmp(buf,"quit",4)){
  97.                     printf("client 请求终止聊天!\n");
  98.                     break;
  99.                 }
  100.                 /*如果输入的字符串只有"\n",即回车,那么请重新输入*/
  101.                 if(!strncmp(buf,"\n",1)){
  102.                     printf("输入的字符只有回车,这个是不正确的!!!\n");
  103.                     goto _retry;
  104.                 }
  105.                 /*如果buf中含有'\n',那么要用strlen(buf)-1,去掉'\n'*/    
  106.                 if(strchr(buf,'\n'))
  107.                     len = send(sockfd,buf,strlen(buf)-1,0);
  108.                 /*如果buf中没有'\n',则用buf的真正长度strlen(buf)*/    
  109.                 else
  110.                     len = send(sockfd,buf,strlen(buf),0);
  111.                 if(len > 0)
  112.                     printf("\t消息发送成功,本次共发送的字节数是:%d\n",len);            
  113.                 else{
  114.                     printf("消息发送失败!\n");
  115.                     break;            
  116.                 }    
  117.             }
  118.         }
  119.     
  120.     }
  121.     /*关闭连接*/
  122.     close(sockfd);

  123.     return 0;
  124. }

4、服务器源代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <sys/socket.h>
  6. #include <arpa/inet.h>
  7. #include <netinet/in.h>
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10. #include <sys/time.h>

  11. #define BUFLEN 1024

  12. int main(int argc, char **argv)
  13. {
  14.     int sockfd, newfd;
  15.     struct sockaddr_in s_addr, c_addr;
  16.     char buf[BUFLEN];
  17.     socklen_t len;
  18.     unsigned int port, listnum;
  19.     fd_set rfds;
  20.     struct timeval tv;    
  21.     int retval,maxfd;
  22.     
  23.     /*建立socket*/
  24.     if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
  25.         perror("socket");
  26.         exit(errno);
  27.     }else
  28.         printf("socket create success!\n");
  29.     /*设置服务器端口*/    
  30.     if(argv[2])
  31.         port = atoi(argv[2]);
  32.     else
  33.         port = 4567;
  34.     /*设置侦听队列长度*/
  35.     if(argv[3])
  36.         listnum = atoi(argv[3]);
  37.     else
  38.         listnum = 3;
  39.     /*设置服务器ip*/
  40.     bzero(&s_addr, sizeof(s_addr));
  41.     s_addr.sin_family = AF_INET;
  42.     s_addr.sin_port = htons(port);
  43.     if(argv[1])
  44.         s_addr.sin_addr.s_addr = inet_addr(argv[1]);
  45.     else
  46.         s_addr.sin_addr.s_addr = INADDR_ANY;
  47.     /*把地址和端口帮定到套接字上*/
  48.     if((bind(sockfd, (struct sockaddr*) &s_addr,sizeof(struct sockaddr))) == -1){
  49.         perror("bind");
  50.         exit(errno);
  51.     }else
  52.         printf("bind success!\n");
  53.     /*侦听本地端口*/
  54.     if(listen(sockfd,listnum) == -1){
  55.         perror("listen");
  56.         exit(errno);    
  57.     }else
  58.         printf("the server is listening!\n");
  59.     while(1){
  60.         printf("*****************聊天开始***************\n");
  61.         len = sizeof(struct sockaddr);
  62.         if((newfd = accept(sockfd,(struct sockaddr*) &c_addr, &len)) == -1){
  63.             perror("accept");        
  64.             exit(errno);
  65.         }else
  66.             printf("正在与您聊天的客户端是:%s: %d\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port));
  67.         while(1){
  68.             /*把可读文件描述符的集合清空*/
  69.             FD_ZERO(&rfds);
  70.             /*把标准输入的文件描述符加入到集合中*/
  71.             FD_SET(0, &rfds);
  72.             maxfd = 0;
  73.             /*把当前连接的文件描述符加入到集合中*/
  74.             FD_SET(newfd, &rfds);
  75.             /*找出文件描述符集合中最大的文件描述符*/    
  76.             if(maxfd < newfd)
  77.                 maxfd = newfd;
  78.             /*设置超时时间*/
  79.             tv.tv_sec = 5;
  80.             tv.tv_usec = 0;
  81.             /*等待聊天*/
  82.             retval = select(maxfd+1, &rfds, NULL, NULL, &tv);
  83.             if(retval == -1){
  84.                 printf("select出错,与该客户端连接的程序将退出\n");
  85.                 break;
  86.             }else if(retval == 0){
  87.                 printf("服务器没有任何输入信息,并且客户端也没有信息到来,waiting...\n");
  88.                 continue;
  89.             }else{
  90.                 /*用户输入信息了,开始处理信息并发送*/
  91.                 if(FD_ISSET(0, &rfds)){
  92.                 _retry:
  93.                     /******发送消息*******/
  94.                     bzero(buf,BUFLEN);
  95.                     /*fgets函数:从流中读取BUFLEN-1个字符*/
  96.                     fgets(buf,BUFLEN,stdin);
  97.                     /*打印发送的消息*/
  98.                     //fputs(buf,stdout);
  99.                     if(!strncasecmp(buf,"quit",4)){
  100.                         printf("server 请求终止聊天!\n");
  101.                         break;
  102.                     }
  103.                     /*如果输入的字符串只有"\n",即回车,那么请重新输入*/
  104.                     if(!strncmp(buf,"\n",1)){
  105.                         printf("输入的字符只有回车,这个是不正确的!!!\n");
  106.                         goto _retry;
  107.                     }    
  108.                     /*如果buf中含有'\n',那么要用strlen(buf)-1,去掉'\n'*/            
  109.                     if(strchr(buf,'\n'))
  110.                         len = send(newfd,buf,strlen(buf)-1,0);
  111.                     /*如果buf中没有'\n',则用buf的真正长度strlen(buf)*/    
  112.                     else
  113.                         len = send(newfd,buf,strlen(buf),0);
  114.                     if(len > 0)
  115.                         printf("\t消息发送成功,本次共发送的字节数是:%d\n",len);            
  116.                     else{
  117.                         printf("消息发送失败!\n");
  118.                         break;            
  119.                     }
  120.                 }
  121.                 /*客户端发来了消息*/
  122.                 if(FD_ISSET(newfd, &rfds)){
  123.                     /******接收消息*******/
  124.                     bzero(buf,BUFLEN);
  125.                     len = recv(newfd,buf,BUFLEN,0);
  126.                     if(len > 0)
  127.                         printf("客户端发来的信息是:%s,共有字节数是: %d\n",buf,len);
  128.                     else{
  129.                         if(len < 0 )
  130.                             printf("接受消息失败!\n");
  131.                         else
  132.                             printf("客户端退出了,聊天终止!\n");
  133.                         break;    
  134.                     }
  135.                 }
  136.             }
  137.         }
  138.         /*关闭聊天的套接字*/
  139.         close(newfd);
  140.         /*是否退出服务器*/
  141.         printf("服务器是否退出程序:y->是;n->否? ");
  142.         bzero(buf, BUFLEN);
  143.         fgets(buf,BUFLEN, stdin);
  144.         if(!strncasecmp(buf,"y",1)){
  145.             printf("server 退出!\n");
  146.             break;
  147.         }
  148.     }
  149.     /*关闭服务器的套接字*/
  150.     close(sockfd);
  151.     return 0;
  152. }

5、编译源代码:
new@new-desktop:~/linux/c$ gcc -Wall async-server.c -o async-server
new@new-desktop:~/linux/c$ gcc -Wall async-client.c -o async-client

6、服务器运行:
new@new-desktop:~/linux/c$ ./async-server 127.0.0.1
socket create success!
bind success!
the server is listening!
*****************聊天开始***************
正在与您聊天的客户端是:127.0.0.1: 37648
服务器没有任何输入信息,并且客户端也没有信息到来,waiting...
hello
消息发送成功,本次共发送的字节数是:5
服务器没有任何输入信息,并且客户端也没有信息到来,waiting...
客户端发来的信息是:renwen,共有字节数是: 6

7、客户端运行:
new@new-desktop:~/linux/c$ ./async-client 127.0.0.1 
socket create success!
conncet success!
客户端没有任何输入信息,并且服务器也没有信息到来,waiting...
服务器发来的消息是:hello,共有字节数是: 5
客户端没有任何输入信息,并且服务器也没有信息到来,waiting...
renwen
消息发送成功,本次共发送的字节数是:6
客户端没有任何输入信息,并且服务器也没有信息到来,waiting...
客户端没有任何输入信息,并且服务器也没有信息到来,waiting...
客户端没有任何输入信息,并且服务器也没有信息到来,waiting...


<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(2043) | 评论(0) | 转发(6) |
给主人留下些什么吧!~~
评论热议
Logo

更多推荐