linux网络编程之用select方法实现io复用(基于udp)

来源:互联网 发布:js 二维数组匹配 编辑:程序博客网 时间:2024/04/25 22:04

1、基本概念


  IO多路复用是指内核一旦发现进程指定的一个或者多个IO条件准备读取,它就通知该进程。IO多路复用适用如下场合:

  (1)当客户处理多个描述字时(一般是交互式输入和网络套接口),必须使用I/O复用。

  (2)当一个客户同时处理多个套接口时,而这种情况是可能的,但很少出现。

  (3)如果一个TCP服务器既要处理监听套接口,又要处理已连接套接口,一般也要用到I/O复用。

  (4)如果一个服务器即要处理TCP,又要处理UDP,一般要使用I/O复用。

  (5)如果一个服务器要处理多个服务或多个协议,一般要使用I/O复用。

  与多进程和多线程技术相比,I/O多路复用技术的最大优势是系统开销小,系统不必创建进程/线程,也不必维护这些进程/线程,从而大大减小了系统的开销。


2、select函数



该函数准许进程指示内核等待多个事件中的任何一个发送,并只在有一个或多个事件发生或经历一段指定的时间后才唤醒。函数原型如下:

#include <sys/select.h>#include <sys/time.h>int select(int maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,const struct timeval *timeout)


返回值:就绪描述符的数目,超时返回0,出错返回-1
函数参数介绍如下:

(1)第一个参数maxfdp1指定待测试的描述字个数,它的值是待测试的最大描述字加1(因此把该参数命名为maxfdp1),描述字0、1、2...maxfdp1-1均将被测试。

因为文件描述符是从0开始的。

(2)中间的三个参数readset、writeset和exceptset指定我们要让内核测试读、写和异常条件的描述字。如果对某一个的条件不感兴趣,就可以把它设为空指针。struct fd_set可以理解为一个集合,这个集合中存放的是文件描述符,可通过以下四个宏进行设置:

          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)timeout告知内核等待所指定描述字中的任何一个就绪可花多少时间。其timeval结构用于指定这段时间的秒数和微秒数。

         struct timeval{                   long tv_sec;   //seconds                   long tv_usec;  //microseconds       };


这个参数有三种可能:


(1)永远等待下去:仅在有一个描述字准备好I/O时才返回。为此,把该参数设置为空指针NULL。
(2)等待一段固定时间:在有一个描述字准备好I/O时返回,但是不超过由该参数所指向的timeval结构中指定的秒数和微秒数。

(3)根本不等待:检查描述字后立即返回,这称为轮询。为此,该参数必须指向一个timeval结构,而且其中的定时器值必须为0。



3 、 实现基于udp客户端到服务端的通信

#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <pthread.h>#include <netinet/in.h>#include <errno.h>#include <sys/time.h>#include <arpa/inet.h>#include <sys/socket.h>#include <sys/select.h>int main(){   char buf[100] = "";   int udp_fd = 0;   struct sockaddr_in addr;   struct sockaddr_in cliaddr;   //对套接字初始化   bzero(&addr, sizeof(addr));   addr.sin_family = AF_INET;   addr.sin_port = htons(8000);   addr.sin_addr.s_addr = htonl(INADDR_ANY);   bzero(&cliaddr, sizeof(cliaddr));   cliaddr.sin_family = AF_INET;   cliaddr.sin_port = htons(8000);   //创建套接口   if ((udp_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)   {      perror("socket create failed\n");      exit(EXIT_FAILURE);   }   puts("socket create success");   //设置端口   if (bind(udp_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)   {       perror("bind fail\n");       close(udp_fd);       exit(EXIT_SUCCESS);   }   puts("bind success");   puts("input:  \"192.168.221.x\" to send msg to body");   while (1)   {       char buf[100] = "";       fd_set rset;//创建文件描述符的聚合变量       FD_ZERO(&rset);       FD_SET(0, &rset);       FD_SET(udp_fd, &rset);       write(1, "chenyu:", 7);       if (select(udp_fd + 1, &rset, NULL, NULL, NULL) > 0)       {          if (FD_ISSET(0, &rset)) //测试0是否可以读写 ,可以的话返回大于0的数据           {              fgets(buf, sizeof(buf), stdin);                            buf[strlen(buf) + 1] = '\0';              char ipbuf[16] = "";      inet_pton(AF_INET, buf + 6, &cliaddr);              printf("\r\033[39m[%s]:\033[39m%s", inet_ntop(AF_INET, &addr.sin_addr, ipbuf, sizeof(ipbuf)), buf);      //iprintf("ip is  %s\n", inet_ntop(AF_INET, &cliaddr.sin_addr, ipbuf, sizeof(ipbuf)));        if (strcmp(buf, "exit") == 0)              {            close(udp_fd);          exit(EXIT_SUCCESS);              }              sendto(udp_fd, buf, strlen(buf), 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));          }          if (FD_ISSET(udp_fd, &rset))          {             puts("has go in rset udp_fd");             struct sockaddr_in addr;     char ipbuf[1024] = "";     socklen_t addrlen = sizeof(addr);             bzero(&addr, sizeof(addr));             puts("receive data start");             recvfrom(udp_fd, buf, 100, 0 , (struct sockaddr*)&addr, &addrlen);             printf("\r\033[34m[%s]:\033[34m%s", inet_ntop(AF_INET, &addr.sin_addr, ipbuf, sizeof(ipbuf)), buf);             puts("receive data end");     }       }   } }





4、运行结果



0 0
原创粉丝点击