首页 > 代码库 > 1高并发服务器:多路IO之select

1高并发服务器:多路IO之select



1 select

Aselect能监听的文件描述符个数受限于FD_SETSIZE,一般为1024,单纯改变进程打开

的文件描述符个数并不能改变select监听文件个数

B:解决1024以下客户端时使用select是很合适的,但如果链接客户端过多,select采用的是轮询模型,会大大降低服务器响应效率,不应在select上投入更多精力

2依赖的头文件

#include <sys/select.h>

/* According to earlier standards */

#include <sys/time.h>

#include <sys/types.h>

#include <unistd.h>

 

int select(int nfds, fd_set *readfds,fd_set *writefds,fd_set *exceptfds, struct timeval *timeout);

说明:

nfds:监控的文件描述符集里最大文件描述符加1,因为此参数会告诉内核检测前多少个文件描述符的状态

readfds:监控有读数据到达文件描述符集合,传入传出参数

writefds:监控写数据到达文件描述符集合,传入传出参数

exceptfds:监控异常发生达文件描述符集合,如带外数据到达异常,传入传出参数

timeout:定时阻塞监控时间,3中情况

  1. NULL,永远等下去

  2. 设置timeval,等待固定时间

  3. 设置timeval里时间均为0,检查描述字后立即返回,轮询。

 

struct timeval {

long tv_sec; /* seconds */

long tv_usec; /*microseconds 微秒;一百万分之一秒*/

};

 

void FD_CLR(int fd,fd_set *set);把文件描述符集合里fd清零

int FD_ISSET(int fd,fd_set *set);测试文件描述符集合里fd是否置1

void FD_SET(int fd,fd_set *set);把文件描述符集合里fd位置1

void FD_ZERO(fd_set *set);   把文件描述符集合里所有位清0

 

select模型

 

案例说明:

Server.c

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<ctype.h>

#include<unistd.h>

#include"wrap.h"

 

#define MAXLINE 80

#define SERV_PORT 8000

 

int main(void)

{

   int i,maxi,maxfd,listenfd,connfd,sockfd;

   /*

    * nreadyselect之后返回的被监控管理的数量,

    * 最大的被管理的文件最大的被管理的文件描述符的

    * 数量是1024

    */

   /*FD_SETSIZE默认为1024*/

   int nready,client[FD_SETSIZE]; /* FD_SETSIZE默认为1024 */

   ssize_t n;

   fd_set rset,allset;

   char buf[MAXLINE];

   /*下面表示的是ip地址的长度*/

   char str[INET_ADDRSTRLEN];   /*#define IN*/

   socklen_t cliaddr_len;

   struct sockaddr_in cliaddr,servaddr;

 

   /*整个服务器只有一个listenfd文件描述符*/

   //1、建立一个socket,案例中是针对TCP

   listenfd = Socket(AF_INET,SOCK_STREAM,0);

   bzero(&servaddr,sizeof(servaddr));

   servaddr.sin_family = AF_INET;

   servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

   servaddr.sin_port = htons(SERV_PORT);

   //2Bind

   Bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

   //3、正在链接的时候最大支持128个,当accept之后就不管了

   Listen(listenfd,20); /*默认最大128*/

   maxfd = listenfd;    /*初始化*/

   maxi = -1;           /*client[]的下标*/

   for(i = 0;i < FD_SETSIZE;i++){

       client[i] = -1;  /*-1初始化client*/

   }

   //将管理的文件描述符集合的内容设置成为0

   FD_ZERO(&allset);

   //listenfd纳入allset中进行管理

   FD_SET(listenfd,&allset);   /*构造select监控文件描述符集*/

   for(;;){

       /*每次循环时都重新设置select监控信号集,这里相当于rset的一个备份*/

       rset = allset;

       //第一个参数是最大描述的最大值+1

       nready = select(maxfd+1,&rset,NULL,NULL,NULL);

       if(nready < 0) {

           perr_exit("select error");

       }

       //判断listenfd是否已经纳入管理

       if(FD_ISSET(listenfd,&rset)) {

           cliaddr_len = sizeof(cliaddr);

           connfd = Accept(listenfd,(struct sockaddr *)&cliaddr,&cliaddr_len);

           //打印ip地址和端口号

           printf("received from %s at PORT %d\n",

               inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,str,sizeof(str)),

               ntohs(cliaddr.sin_port));

           for(i = 0;i < FD_SETSIZE;i++) {

               if(client[i] < 0) {

                   client[i] = connfd;/*保存accept返回的文件描述符到client[]*/

                   break;

               }

           }

       }   /*达到select能监控的文件个数上限1024*/

           if(i == FD_SETSIZE) {

               fputs("to many clients\n",stderr);

               exit(1);

           }

           /*添加一个新的文件描述符到监控信号集里*/

           FD_SET(connfd,&allset);

           if(connfd > maxfd)

               maxfd = connfd; /*select第一个参数需要*/

           if(i > maxi)

               maxi = i;  /*更新client[]最大下标值*/

           if(--nready == 0)

               /*如果没有更多的就绪文件描述符,继续回到上面select

                * 负责处理未完成的就绪文件描述符*/

               continue;

   }

 

   for(i = 0;i< maxi;i++) {

       if((sockfd = client[i]) < 0)

           continue;

       if(FD_ISSET(sockfd,&rset)) {

           if((n=Read(sockfd,buf,MAXLINE)) == 0) {

               /*client关闭链接时,服务器端也关闭链接*/

               Close(sockfd);

               /*解除select监控文件描述符*/

               FD_CLR(sockfd,&allset);

               client[i] = -1;

           } else {

               int j;

               for(j = 0; j< n;j++) {

                   buf[j] = toupper(buf[j]);

               }

               Write(sockfd,buf,n);

           }

 

           if(--nready == 0)

               break;

       }

   }

 

   Close(listenfd);

   return 0;

}

Client.c

#include <stdio.h>

#include <string.h>

#include <unistd.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include"wrap.h"

 

#define MAXLINE 80

#define SERV_PORT 8000

 

int main(void) {

   struct sockaddr_in servaddr;

   char buf[MAXLINE];

   int sockfd,n;

   //1.Socket

   sockfd = Socket(AF_INET,SOCK_STREAM,0);

   //设置ip和端口号等相关信息

   bzero(&servaddr,sizeof(servaddr));

   servaddr.sin_family = AF_INET;

   inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr);

   servaddr.sin_port = htons(SERV_PORT);

   //2.建立连接

   Connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

   

   while(fgets(buf,MAXLINE,stdin) != NULL) {

       //3.Write数据

       Write(sockfd,buf,strlen(buf));

       n = Read(sockfd,buf,MAXLINE);

       if(n == 0) {

           printf("the other side has been closed.\n");

       } else {

           Write(STDOUT_FILENO,buf,n);

       }

   }

 

   Close(sockfd);

   return 0;

}

Wrap.h

#ifndef __WRAP_H_

#define __WRAP_H_

 

void perr_exit(const char *s);

int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr);

void Bind(int fd, const struct sockaddr *sa, socklen_t salen);

void Connect(int fd, const struct sockaddr *sa, socklen_t salen);

void Listen(int fd, int backlog);

int Socket(int family, int type, int protocol);

ssize_t Read(int fd, void *ptr, size_t nbytes);

ssize_t Write(int fd, const void *ptr, size_t nbytes);

void Close(int fd);

ssize_t Readn(int fd, void *vptr, size_t n);

ssize_t Writen(int fd, const void *vptr, size_t n);

static ssize_t my_read(int fd, char *ptr);

ssize_t Readline(int fd, void *vptr, size_t maxlen);

 

#endif

Wrap.c

#include <stdlib.h>

#include <errno.h>

#include <sys/socket.h>

 

void perr_exit(const char *s)

{

        perror(s);

        exit(1);

}

 

int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)

{

        int n;

 

again:

        if ( (n = accept(fd, sa, salenptr)) < 0) {

                  if ((errno == ECONNABORTED) || (errno == EINTR))

                           goto again;

                  else

                           perr_exit("accept error");

        }

        return n;

}

 

void Bind(int fd, const struct sockaddr *sa, socklen_t salen)

{

        if (bind(fd, sa, salen) < 0)

                  perr_exit("bind error");

}

 

void Connect(int fd, const struct sockaddr *sa, socklen_t salen)

{

        if (connect(fd, sa, salen) < 0)

                  perr_exit("connect error");

}

 

void Listen(int fd, int backlog)

{

        if (listen(fd, backlog) < 0)

                  perr_exit("listen error");

}

 

int Socket(int family, int type, int protocol)

{

        int n;

 

        if ( (n = socket(family, type, protocol)) < 0)

                  perr_exit("socket error");

        return n;

}

 

ssize_t Read(int fd, void *ptr, size_t nbytes)

{

        ssize_t n;

 

again:

        if ( (n = read(fd, ptr, nbytes)) == -1) {

                  if (errno == EINTR)

                           goto again;

                  else

                           return -1;

        }

        return n;

}

 

ssize_t Write(int fd, const void *ptr, size_t nbytes)

{

        ssize_t n;

 

again:

        if ( (n = write(fd, ptr, nbytes)) == -1) {

                  if (errno == EINTR)

                           goto again;

                  else

                           return -1;

        }

        return n;

}

 

void Close(int fd)

{

        if (close(fd) == -1)

                  perr_exit("close error");

}

ssize_t Readn(int fd, void *vptr, size_t n)

{

        size_t  nleft;

        ssize_t nread;

        char   *ptr;

 

        ptr = vptr;

        nleft = n;

        while (nleft > 0) {

                  if ( (nread = read(fd, ptr, nleft)) < 0) {

                           if (errno == EINTR)

                                    nread = 0;

                           else

                                    return -1;

                  } else if (nread == 0)

                           break;

 

                  nleft -= nread;

                  ptr += nread;

        }

        return n - nleft;

}

 

ssize_t Writen(int fd, const void *vptr, size_t n)

{

        size_t nleft;

        ssize_t nwritten;

        const char *ptr;

 

        ptr = vptr;

        nleft = n;

        while (nleft > 0) {

                  if ( (nwritten = write(fd, ptr, nleft)) <= 0) {

                           if (nwritten < 0 && errno == EINTR)

                                    nwritten = 0;

                           else

                                    return -1;

                  }

 

                  nleft -= nwritten;

                  ptr += nwritten;

        }

        return n;

}

static ssize_t my_read(int fd, char *ptr)

{

        static int read_cnt;

        static char *read_ptr;

        static char read_buf[100];

 

        if (read_cnt <= 0) {

again:

                  if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {

                           if (errno == EINTR)

                                    goto again;

                           return -1;

                  } else if (read_cnt == 0)

                           return 0;

                  read_ptr = read_buf;

        }

        read_cnt--;

        *ptr = *read_ptr++;

        return 1;

}

 

ssize_t Readline(int fd, void *vptr, size_t maxlen)

{

        ssize_t n, rc;

        char    c, *ptr;

 

        ptr = vptr;

        for (n = 1; n < maxlen; n++) {

                  if ( (rc = my_read(fd, &c)) == 1) {

                           *ptr++ = c;

                           if (c  == ‘\n‘)

                                    break;

                  } else if (rc == 0) {

                           *ptr = 0;

                           return n - 1;

                  } else

                           return -1;

        }

        *ptr  = 0;

        return n;

}

 

1高并发服务器:多路IO之select