unix网络模型

来源:互联网 发布:js的面试题 编辑:程序博客网 时间:2024/04/29 03:21


转载自http://blog.csdn.net/yfkiss/article/details/7516589

IO模型在Richard Stevens的《UNIX网络编程,第一卷》(程序猿必备!)一书中有非常详尽的描述,以下简要介绍,并给出代码示例。

另外比较好的总结性blog,推荐:
使用异步 I/O 大大提高应用程序的性能
IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇)

常见网络IO模型:阻塞式IO、无阻塞式IO、IO复用、异步IO、信号驱动

阻塞式IO:
在一个进程发出IO请求后,进入阻塞状态,直到内核返回数据,才重新运行,如图:

代码
sever端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netinet/in.h>  
  6. #include <sys/socket.h>  
  7. #include <unistd.h>  
  8.   
  9. int main()  
  10. {  
  11.     int sockfd, new_fd;  
  12.     int sin_size, numbytes;  
  13.     struct sockaddr_in addr, cliaddr;  
  14.       
  15.     //创建socket  
  16.     if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)  
  17.     {  
  18.         perror("createSocket");  
  19.         return -1;  
  20.     }  
  21.       
  22.     //初始化socket结构  
  23.     memset(&addr, 0, sizeof(addr));  
  24.     addr.sin_family = AF_INET;  
  25.     addr.sin_port = htons(7092);  
  26.     addr.sin_addr.s_addr = htonl(INADDR_ANY);  
  27.       
  28.     //绑定套接口  
  29.     if(bind(sockfd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1)  
  30.     {  
  31.         perror("bind");  
  32.         return -1;  
  33.     }  
  34.       
  35.     //创建监听套接口  
  36.     if(listen(sockfd,10)==-1)  
  37.     {  
  38.         perror("listen");  
  39.         return -1;  
  40.     }  
  41.       
  42.       
  43.     printf("server is running!\n");  
  44.       
  45.     char buff[1024];  
  46.     //等待连接  
  47.     while(1)   
  48.     {  
  49.         sin_size = sizeof(struct sockaddr_in);  
  50.           
  51.         //接受连接  
  52.         if((new_fd = accept(sockfd, (struct sockaddr *)&cliaddr, (socklen_t*)&sin_size))==-1)  
  53.         {  
  54.             perror("accept");  
  55.             return -1;  
  56.         }  
  57.           
  58.         //生成一个子进程来完成和客户端的会话,父进程继续监听  
  59.         if(!fork())  
  60.         {  
  61.             //读取客户端发来的信息  
  62.             memset(buff,0,sizeof(buff));  
  63.             if((numbytes = recv(new_fd,buff,sizeof(buff),0))==-1)  
  64.             {  
  65.                 perror("recv");  
  66.                 return -1;  
  67.             }  
  68.             printf("buff=%s\n",buff);  
  69.               
  70.             //将从客户端接收到的信息再发回客户端  
  71.             if(send(new_fd,buff,strlen(buff),0)==-1)  
  72.             {  
  73.                 perror("send");  
  74.             }  
  75.       
  76.             close(new_fd);  
  77.             return 0;  
  78.         }  
  79.         //父进程关闭new_fd  
  80.         close(new_fd);  
  81.     }  
  82.     close(sockfd);  
  83. }  
client端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netdb.h>  
  6. #include <sys/types.h>  
  7. #include <netinet/in.h>  
  8. #include <sys/socket.h>  
  9. #include <unistd.h>  
  10.   
  11. int main(int argc,char *argv[])  
  12. {  
  13.     if(argc!=3)  
  14.     {  
  15.         printf("%s: input IP & port\n",argv[0]);  
  16.         return 1;  
  17.     }  
  18.     int sockfd,numbytes;  
  19.     char buf[100] = "hello world";  
  20.     struct hostent *he;  
  21.     struct sockaddr_in their_addr;  
  22.       
  23.     //将基本名字和地址转换  
  24.     he = gethostbyname(argv[1]);  
  25.       
  26.     //建立一个TCP套接口  
  27.     if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1)  
  28.     {  
  29.         perror("socket");  
  30.         exit(1);  
  31.     }  
  32.       
  33.     //初始化结构体  
  34.     their_addr.sin_family = AF_INET;  
  35.     their_addr.sin_port = htons(atoi(argv[2]));  
  36.     their_addr.sin_addr = *((struct in_addr *)he->h_addr);  
  37.     bzero(&(their_addr.sin_zero),8);  
  38.       
  39.     //和服务器建立连接  
  40.     if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1)  
  41.     {  
  42.         perror("connect");  
  43.         exit(1);  
  44.     }  
  45.       
  46.     //向服务器发送字符串  
  47.     if(send(sockfd,buf,strlen(buf),0)==-1)  
  48.     {  
  49.         perror("send");  
  50.         exit(1);  
  51.     }  
  52.     memset(buf,0,sizeof(buf));  
  53.       
  54.     //接受从服务器返回的信息  
  55.     if((numbytes = recv(sockfd,buf,100,0))==-1)  
  56.     {  
  57.         perror("recv");  
  58.         exit(1);  
  59.     }  
  60.       
  61.     close(sockfd);  
  62.     return 0;  
  63. }  

运行:
$ ./bin/server 
server is running!
buff=hello world
buff=hello world

$ ./bin/client 10.32.49.10 7092
$ ./bin/client 10.32.49.10 7092

无阻塞式IO:
在一个进程发出IO请求后,不阻塞,如果数据没有准备好,就直接返回错误码,如图:

可以通过fcntl控制socket描述符属性。
int flags;
flag=fcntl(sockfd,F_GETFL,0);
fcntl(sockfd,F_SETFL,flag|O_NONBLOCK)

非阻塞式I/O模型对4种I/O操作返回的错误
读操作:接收缓冲区无数据时返回EWOULDBLOCK
写操作:发送缓冲区无空间时返回EWOULDBLOCK;空间不够时部分拷贝,返回实际拷贝字节数
建立连接:启动3次握手,立刻返回错误EINPROGRESS;服务器客户端在同一主机上connect立即返回成功
接受连接:没有新连接返回EWOULDBLOCK

代码:
server端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netinet/in.h>  
  6. #include <sys/socket.h>  
  7. #include <unistd.h>  
  8. #include <fcntl.h>  
  9.   
  10. int main()  
  11. {  
  12.     int sockfd, new_fd;  
  13.     int sin_size;  
  14.     struct sockaddr_in addr, cliaddr;  
  15.       
  16.     //创建socket  
  17.     if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)  
  18.     {  
  19.         perror("createSocket");  
  20.         return -1;  
  21.     }  
  22.       
  23.     //初始化socket结构  
  24.     memset(&addr, 0, sizeof(addr));  
  25.     addr.sin_family = AF_INET;  
  26.     addr.sin_port = htons(7092);  
  27.     addr.sin_addr.s_addr = htonl(INADDR_ANY);  
  28.       
  29.     //绑定套接口  
  30.     if(bind(sockfd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1)  
  31.     {  
  32.         perror("bind");  
  33.         return -1;  
  34.     }  
  35.       
  36.     //创建监听套接口  
  37.     if(listen(sockfd,10)==-1)  
  38.     {  
  39.         perror("listen");  
  40.         return -1;  
  41.     }  
  42.       
  43.     printf("server is running!\n");  
  44.       
  45.     char buff[1024];  
  46.     //等待连接  
  47.     while(1)   
  48.     {  
  49.         sin_size = sizeof(struct sockaddr_in);  
  50.           
  51.         //接受连接  
  52.         if((new_fd = accept(sockfd, (struct sockaddr *)&cliaddr, (socklen_t*)&sin_size))==-1)  
  53.         {  
  54.             perror("accept");  
  55.             return -1;  
  56.         }  
  57.               
  58.         //生成一个子进程来完成和客户端的会话,父进程继续监听  
  59.         if(!fork())  
  60.         {  
  61.             //设置new_fd无阻塞属性  
  62.             int flags;  
  63.             if((flags=fcntl(new_fd, F_GETFL, 0))<0)    
  64.             {  
  65.                 perror("fcntl F_GETFL");    
  66.             }  
  67.             flags |= O_NONBLOCK;    
  68.             if(fcntl(new_fd, F_SETFL,flags)<0)    
  69.             {  
  70.                 perror("fcntl F_SETFL");    
  71.             }  
  72.               
  73.             //读取客户端发来的信息  
  74.             memset(buff,0,sizeof(buff));  
  75.             while(1)  
  76.             {  
  77.                 if((recv(new_fd,buff,sizeof(buff),0)) < 0)  
  78.                 {  
  79.                     if(errno==EWOULDBLOCK)  
  80.                     {  
  81.                         perror("recv error, wait....");  
  82.                         sleep(1);  
  83.                         continue;  
  84.                     }  
  85.                 }  
  86.                 else  
  87.                 {  
  88.                     printf("buff=%s\n",buff);  
  89.                 }     
  90.                 break;  
  91.             }  
  92.   
  93.             //发送数据  
  94.             while(1)  
  95.             {  
  96.                 if(send(new_fd,buff,strlen(buff),0) < 0)  
  97.                 {  
  98.                     if(errno==EWOULDBLOCK)  
  99.                     {  
  100.                         perror("send error, wait....");  
  101.                         sleep(1);  
  102.                         continue;  
  103.                     }  
  104.                 }  
  105.                 else  
  106.                 {  
  107.                     printf("buff=%s\n",buff);  
  108.                 }     
  109.                 break;  
  110.             }  
  111.       
  112.             close(new_fd);  
  113.             return 0;  
  114.         }  
  115.         //父进程关闭new_fd  
  116.         close(new_fd);  
  117.     }  
  118.     close(sockfd);  
  119. }  

client端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netdb.h>  
  6. #include <sys/types.h>  
  7. #include <netinet/in.h>  
  8. #include <sys/socket.h>  
  9. #include <unistd.h>  
  10.   
  11. int main(int argc,char *argv[])  
  12. {  
  13.     if(argc!=3)  
  14.     {  
  15.         printf("%s: input IP & port\n",argv[0]);  
  16.         return 1;  
  17.     }  
  18.     int sockfd,numbytes;  
  19.     char buf[100] = "hello world";  
  20.     struct hostent *he;  
  21.     struct sockaddr_in their_addr;  
  22.       
  23.     //将基本名字和地址转换  
  24.     he = gethostbyname(argv[1]);  
  25.       
  26.     //建立一个TCP套接口  
  27.     if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1)  
  28.     {  
  29.         perror("socket");  
  30.         exit(1);  
  31.     }  
  32.       
  33.     //初始化结构体  
  34.     their_addr.sin_family = AF_INET;  
  35.     their_addr.sin_port = htons(atoi(argv[2]));  
  36.     their_addr.sin_addr = *((struct in_addr *)he->h_addr);  
  37.     bzero(&(their_addr.sin_zero),8);  
  38.       
  39.     //和服务器建立连接  
  40.     if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1)  
  41.     {  
  42.         perror("connect");  
  43.         exit(1);  
  44.     }  
  45.   
  46.     sleep(5);  
  47.       
  48.     //向服务器发送字符串  
  49.     if(send(sockfd,buf,strlen(buf),0)==-1)  
  50.     {  
  51.         perror("send");  
  52.         exit(1);  
  53.     }  
  54.     memset(buf,0,sizeof(buf));  
  55.       
  56.       
  57.     sleep(5);  
  58.       
  59.     //接受从服务器返回的信息  
  60.     if((numbytes = recv(sockfd,buf,100,0))==-1)  
  61.     {  
  62.         perror("recv");  
  63.         exit(1);  
  64.     }  
  65.       
  66.     close(sockfd);  
  67.     return 0;  
  68. }  

运行:
$ ./bin/server 
server is running!
recv error, wait....: Resource temporarily unavailable
recv error, wait....: Resource temporarily unavailable
recv error, wait....: Resource temporarily unavailable
recv error, wait....: Resource temporarily unavailable
recv error, wait....: Resource temporarily unavailable
buff=hello world
buff=hello world

$ ./bin/client 10.32.49.10 7092

IO复用:
IO复用阻塞在select、poll或epoll这样的系统调用上,通过这种方式,在不使用多线程的前提下,单个进程可以同时处理多个网络连接的IO。如图:

代码
sever端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netinet/in.h>  
  6. #include <sys/socket.h>  
  7. #include <unistd.h>  
  8. #include <fcntl.h>  
  9. #include <netdb.h>  
  10. #include <sys/epoll.h>  
  11.   
  12. #define MAXEVENT 1024  
  13.   
  14. int create_server_socket(int& sockfd)  
  15. {  
  16.     struct sockaddr_in addr;  
  17.       
  18.     //创建socket  
  19.     if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)  
  20.     {  
  21.         perror("createSocket");  
  22.         return -1;  
  23.     }  
  24.       
  25.     //初始化socket结构  
  26.     memset(&addr, 0, sizeof(addr));  
  27.     addr.sin_family = AF_INET;  
  28.     addr.sin_port = htons(7092);  
  29.     addr.sin_addr.s_addr = htonl(INADDR_ANY);  
  30.       
  31.     //绑定套接口  
  32.     if(bind(sockfd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1)  
  33.     {  
  34.         perror("bind");  
  35.         return -1;  
  36.     }  
  37.       
  38.     //创建监听套接口  
  39.     if(listen(sockfd,10)==-1)  
  40.     {  
  41.         perror("listen");  
  42.         return -1;  
  43.     }  
  44.       
  45.     return 0;     
  46. }  
  47.   
  48. int set_socket_non_blocking(int fd)  
  49. {  
  50.     int flags, s;  
  51.       
  52.     flags = fcntl (fd, F_GETFL, 0);  
  53.     if (flags == -1)  
  54.     {  
  55.         perror ("fcntl F_GETFL failed");  
  56.         return -1;  
  57.     }  
  58.       
  59.     flags |= O_NONBLOCK;  
  60.     s = fcntl (fd, F_SETFL, flags);  
  61.     if (s == -1)  
  62.     {  
  63.         perror ("fcntl F_SETFL failed");  
  64.         return -1;  
  65.     }  
  66.       
  67.     return 0;  
  68. }  
  69.   
  70. int main()  
  71. {  
  72.     int sockfd, efd;  
  73.     struct epoll_event event;  
  74.     struct epoll_event *events;   
  75.     int s;  
  76.       
  77.     if(create_server_socket(sockfd) != 0)  
  78.     {  
  79.         perror("create server sock failed\n");  
  80.         return 1;  
  81.     }  
  82.     set_socket_non_blocking(sockfd);  
  83.       
  84.     printf("server is running!\n");  
  85.   
  86.     //创建一个epoll的句柄  
  87.     //int epoll_create(int size)    
  88.     //Since Linux 2.6.8, the size argument is unused. (The kernel dynamically sizes the required data structures without needing this initial hint.)  
  89.     efd = epoll_create(MAXEVENT);  
  90.     if (efd == -1)  
  91.     {  
  92.         perror ("epoll_create");  
  93.         abort ();  
  94.     }  
  95.   
  96.     //注册新事件到epoll efd  
  97.     event.data.fd = sockfd;  
  98.     event.events = EPOLLIN | EPOLLET;  
  99.     s = epoll_ctl(efd, EPOLL_CTL_ADD, sockfd, &event);  
  100.     if (s == -1)  
  101.     {  
  102.         perror ("epoll_ctl EPOLL_CTL_ADD failed");  
  103.         abort ();  
  104.     }  
  105.       
  106.     events = (epoll_event*)calloc(MAXEVENT, sizeof(event));  
  107.       
  108.     while (1)  
  109.     {  
  110.         int n, i;  
  111.         n = epoll_wait(efd, events, MAXEVENT, -1);  
  112.         for (i = 0; i < n; i++)  
  113.         {  
  114.             //fd error  
  115.             if ((events[i].events & EPOLLERR) ||  
  116.                 (events[i].events & EPOLLHUP) ||  
  117.               (!(events[i].events & EPOLLIN)))  
  118.             {  
  119.                 perror("epoll error\n");  
  120.                 close (events[i].data.fd);  
  121.                 continue;  
  122.             }  
  123.             //新连接  
  124.             else if (sockfd == events[i].data.fd)  
  125.             {  
  126.                 while (1)  
  127.                 {  //当使用epoll的ET模型来工作时,当产生了一个EPOLLIN事件后,  读数据的时候需要考   //虑的是当recv()返回的大小如果等于请求的大小,那么很有可能是缓冲区还有数据未读                      //完,也意味着该次事件还没有处理完,所以还需要再次读取
  128.                     struct sockaddr in_addr;  
  129.                     socklen_t in_len;  
  130.                     int infd;  
  131.                     char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];  
  132.                       
  133.                     //接受连接  
  134.                     in_len = sizeof(in_addr);  
  135.                     infd = accept(sockfd, &in_addr, &in_len);  
  136.                     if (infd == -1)  
  137.                     {  
  138.                         if ((errno == EAGAIN) ||  
  139.                           (errno == EWOULDBLOCK))  
  140.                         {  
  141.                             //已接受所有连接  
  142.                             break;  
  143.                         }  
  144.                         else  
  145.                         {  
  146.                             perror ("accept");  
  147.                             break;  
  148.                         }  
  149.                     }  
  150.                       
  151.                     s = getnameinfo (&in_addr, in_len,  
  152.                                    hbuf, sizeof hbuf,  
  153.                                    sbuf, sizeof sbuf,  
  154.                                    NI_NUMERICHOST | NI_NUMERICSERV);  
  155.                     if (s == 0)  
  156.                     {  
  157.                       printf("Accepted connection on descriptor %d "  
  158.                              "(host=%s, port=%s)\n", infd, hbuf, sbuf);  
  159.                     }  
  160.                       
  161.                     /* 设置新接受的socket连接无阻塞*/  
  162.                     s = set_socket_non_blocking (infd);  
  163.                     if (s == -1)  
  164.                     {  
  165.                     return 1;  
  166.                     }  
  167.                       
  168.                     //注册新事件到epoll  
  169.                     event.data.fd = infd;  
  170.                     event.events = EPOLLIN | EPOLLET;  
  171.                     s = epoll_ctl(efd, EPOLL_CTL_ADD, infd, &event);  
  172.                     if (s == -1)  
  173.                     {  
  174.                       perror ("epoll_ctl");  
  175.                       return 1;  
  176.                     }  
  177.                 }  
  178.                 continue;  
  179.             }  
  180.             //数据可读  
  181.             else  
  182.             {  
  183.               int done = 0;  
  184.               while (1)  
  185.               {  
  186.   //当使用epoll的ET模型来工作时,当产生了一个EPOLLIN事件后,  读数据的时候需要考          //虑的是当recv()返回的大小如果等于请求的大小,那么很有可能是缓冲区还有数据未读                     //完,也意味着该次事件还没有处理完,所以还需要再次读取
  187.                   ssize_t count;  
  188.                   char buf[512];  
  189.                   count = read(events[i].data.fd, buf, sizeof(buf));  
  190.                   if(count == -1)  
  191.                   {  
  192.                       //出错,如果等于EAGAIN表示数据读完  
  193.                       if (errno != EAGAIN)  
  194.                       {  
  195.                           perror ("read");  
  196.                           done = 1;  
  197.                       }  
  198.                       break;  
  199.                   }  
  200.                   else if(count == 0)  
  201.                   {  
  202.                       /* End of file. The remote has closed the 
  203.                          connection. */  
  204.                       done = 1;  
  205.                       break;  
  206.                    }  
  207.   
  208.                   printf("recv: %s\n", buf);  
  209.                 }  
  210.   
  211.               if (done)  
  212.               {  
  213.                   printf ("Closed connection on descriptor %d\n", events[i].data.fd);  
  214.                   close (events[i].data.fd);  
  215.               }  
  216.             }  
  217.         }  
  218.     }  
  219.   
  220.   free (events);  
  221.   close(sockfd);  
  222.   return 0;  
  223. }  
client端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netdb.h>  
  6. #include <sys/types.h>  
  7. #include <netinet/in.h>  
  8. #include <sys/socket.h>  
  9. #include <unistd.h>  
  10.   
  11. int main(int argc,char *argv[])  
  12. {  
  13.     if(argc!=3)  
  14.     {  
  15.         printf("%s: input IP & port\n",argv[0]);  
  16.         return 1;  
  17.     }  
  18.     int sockfd,numbytes;  
  19.     char buf[100] = "hello world";  
  20.     struct hostent *he;  
  21.     struct sockaddr_in their_addr;  
  22.       
  23.     //将基本名字和地址转换  
  24.     he = gethostbyname(argv[1]);  
  25.       
  26.     //建立一个TCP套接口  
  27.     if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1)  
  28.     {  
  29.         perror("socket");  
  30.         exit(1);  
  31.     }  
  32.       
  33.     //初始化结构体  
  34.     their_addr.sin_family = AF_INET;  
  35.     their_addr.sin_port = htons(atoi(argv[2]));  
  36.     their_addr.sin_addr = *((struct in_addr *)he->h_addr);  
  37.     bzero(&(their_addr.sin_zero),8);  
  38.       
  39.     //和服务器建立连接  
  40.     if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1)  
  41.     {  
  42.         perror("connect");  
  43.         exit(1);  
  44.     }  
  45.   
  46.       
  47.     //向服务器发送字符串  
  48.     while(1)  
  49.     {  
  50.         if(send(sockfd,buf,strlen(buf),0)==-1)  
  51.         {  
  52.             perror("send");  
  53.             exit(1);  
  54.         }  
  55.         sleep(2);  
  56.     }  
  57.     memset(buf,0,sizeof(buf));  
  58.       
  59.     close(sockfd);  
  60.     return 0;  
  61. }  

运行:
$ ./bin/server    
server is running!
Accepted connection on descriptor 5 (host=10.32.49.10, port=39001)
recv: hello world
recv: hello world
recv: hello world
recv: hello world

./bin/client 10.32.49.10 7092

异步IO:
在一个进程发出IO请求后直接返回,内核在整个操作(包括将数据复制到进程缓冲区)完成后通知进程,如图:

代码
server端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netinet/in.h>  
  6. #include <sys/socket.h>  
  7. #include <unistd.h>  
  8. #include <fcntl.h>  
  9. #include <aio.h>  
  10. #include <pthread.h>  
  11.   
  12. #define BUF_SIZE 1024  
  13.   
  14.   
  15. void aio_completion_handler(sigval_t sigval);  
  16.   
  17. void setup_io(int fd, aiocb& my_aiocb)  
  18. {  
  19.     //初始化AIO请求  
  20.     bzero( (char *)&my_aiocb, sizeof(struct aiocb) );  
  21.     my_aiocb.aio_fildes = fd;  
  22.     my_aiocb.aio_buf = malloc(BUF_SIZE+1);  
  23.     my_aiocb.aio_nbytes = BUF_SIZE;  
  24.     my_aiocb.aio_offset = 0;  
  25.       
  26.     //设置线程回调函数  
  27.     my_aiocb.aio_sigevent.sigev_notify = SIGEV_THREAD;  
  28.     my_aiocb.aio_sigevent.sigev_notify_function = aio_completion_handler;  
  29.     my_aiocb.aio_sigevent.sigev_notify_attributes = NULL;  
  30.     my_aiocb.aio_sigevent.sigev_value.sival_ptr = &my_aiocb;  
  31. }  
  32.   
  33. //回调函数  
  34. void aio_completion_handler(sigval_t sigval)  
  35. {  
  36.     struct aiocb *req;  
  37.     int ret;  
  38.       
  39.     req = (struct aiocb *)sigval.sival_ptr;  
  40.       
  41.     if (aio_error(req) == 0)   
  42.     {  
  43.         if((ret = aio_return(req)) > 0)  
  44.         {  
  45.             printf("Thread id %u recv:%s\n", (unsigned int)pthread_self(), (char*)req->aio_buf);  
  46.         }  
  47.     }  
  48.   
  49.     char* buf = (char*)req->aio_buf;  
  50.       
  51.     if(send(req->aio_fildes, buf, strlen(buf), 0) == -1)  
  52.     {  
  53.         perror("send");  
  54.         return;  
  55.     }  
  56.   
  57.     close(req->aio_fildes);  
  58.   
  59.     return;  
  60. }  
  61.   
  62. int main()  
  63. {  
  64.     int sockfd;  
  65.     int sin_size;  
  66.     struct sockaddr_in addr, cliaddr;  
  67.       
  68.     //创建socket  
  69.     if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)  
  70.     {  
  71.         perror("createSocket");  
  72.         return -1;  
  73.     }  
  74.       
  75.     //初始化socket结构  
  76.     memset(&addr, 0, sizeof(addr));  
  77.     addr.sin_family = AF_INET;  
  78.     addr.sin_port = htons(7092);  
  79.     addr.sin_addr.s_addr = htonl(INADDR_ANY);  
  80.       
  81.     //绑定套接口  
  82.     if(bind(sockfd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1)  
  83.     {  
  84.         perror("bind");  
  85.         return -1;  
  86.     }  
  87.       
  88.     //创建监听套接口  
  89.     if(listen(sockfd,10)==-1)  
  90.     {  
  91.         perror("listen");  
  92.         return -1;  
  93.     }  
  94.       
  95.       
  96.     printf("server is running!\n");  
  97.       
  98.     //等待连接  
  99.     while(1)   
  100.     {  
  101.         int new_fd;  
  102.         struct aiocb my_aiocb;  
  103.         sin_size = sizeof(struct sockaddr_in);  
  104.           
  105.         //接受连接  
  106.         if((new_fd = accept(sockfd, (struct sockaddr *)&cliaddr, (socklen_t*)&sin_size))==-1)  
  107.         {  
  108.             perror("accept");  
  109.             return -1;  
  110.         }  
  111.   
  112.         printf("Thread id %u accept connect, fd: %d\n", (unsigned int)pthread_self(), new_fd);  
  113.           
  114.         setup_io(new_fd, my_aiocb);  
  115.         aio_read(&my_aiocb);  
  116.     }  
  117.     close(sockfd);  
  118. }  

client端:
[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. #include <netdb.h>  
  6. #include <sys/types.h>  
  7. #include <netinet/in.h>  
  8. #include <sys/socket.h>  
  9. #include <unistd.h>  
  10.   
  11. int main(int argc,char *argv[])  
  12. {  
  13.     if(argc!=3)  
  14.     {  
  15.         printf("%s: input IP & port\n",argv[0]);  
  16.         return 1;  
  17.     }  
  18.     int sockfd,numbytes;  
  19.     char buf[100] = "hello world";  
  20.     struct hostent *he;  
  21.     struct sockaddr_in their_addr;  
  22.       
  23.     //将基本名字和地址转换  
  24.     he = gethostbyname(argv[1]);  
  25.       
  26.     //建立一个TCP套接口  
  27.     if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1)  
  28.     {  
  29.         perror("socket");  
  30.         exit(1);  
  31.     }  
  32.       
  33.     //初始化结构体  
  34.     their_addr.sin_family = AF_INET;  
  35.     their_addr.sin_port = htons(atoi(argv[2]));  
  36.     their_addr.sin_addr = *((struct in_addr *)he->h_addr);  
  37.     bzero(&(their_addr.sin_zero),8);  
  38.       
  39.     //和服务器建立连接  
  40.     if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1)  
  41.     {  
  42.         perror("connect");  
  43.         exit(1);  
  44.     }  
  45.   
  46.       
  47.     //向服务器发送字符串  
  48.     if(send(sockfd,buf,strlen(buf),0)==-1)  
  49.     {  
  50.         perror("send");  
  51.         exit(1);  
  52.     }  
  53.    
  54.         //接收数据  
  55.     if((numbytes = recv(sockfd, buf, 100, 0)) == -1)  
  56.     {  
  57.         perror("recv");  
  58.         return 1;  
  59.     }  
  60.   
  61.     printf("recv: %s\n", buf);  
  62.       
  63.     close(sockfd);  
  64.     return 0;  
  65. }  

运行:
$ ./bin/server 
server is running!
Thread id 2505492000 accept connect, fd: 4
Thread id 1084246368 recv:hello world
(注意:线程ID不一样)

$ ./bin/client 10.32.49.10 7092
recv: hello world


信号驱动IO:
使用信号驱动I/O时,当网络套接字可读后,内核通过发送SIGIO信号通知应用进程,于是应用可以开始读取数据。如图:

为了让套接字描述符可以工作于信号驱动I/O模式,应用进程必须完成如下三步设置: 
1.注册SIGIO信号处理程序。(安装信号处理器) 
2.使用fcntl的F_SETOWN命令,设置套接字所有者。(设置套接字的所有者) 
3.使用fcntl的F_SETFL命令,置O_ASYNC标志,允许套接字信号驱动I/O。(允许这个套接字进行信号输入输出)
注意,必须保证在设置套接字所有者之前,向系统注册信号处理程序,否则就有可能在fcntl调用后,信号处理程序注册前内核向应用交付SIGIO信号,导致应用丢失此信号。

在UDP编程中使用信号驱动I/O,此时SIGIO信号产生于下面两种情况: 
套接字收到一个数据报。 
套接字上发生了异步错误。 
因此,当应用因为收到一个UDP数据报而产生的SIGIO时,要么可以调用recvfrom读取该数据报,要么得到一个异步错误。 
对于TCP编程,信号驱动I/O就没有太大意义了,因为对于流式套接字而言,有很多情况都可以导致SIGIO产生,而应用又无法区分是什么具体情况导致该信号产生的