网络编程之select

大耗子 2020年03月10日 192次浏览

文章链接:https://codemouse.online/archives/2020-03-10-201000

函数说明

  • void FD_CLR(int fd, fd_set *set);

    将fd文件描述符从集合中删除

  • int FD_ISSET(int fd, fd_set *set);

    判断该fd是否在集合内

  • void FD_SET(int fd, fd_set *set);

    将fd添加到集合中

  • void FD_ZERO(fd_set *set);

    将集合清空

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

    对fd_set中的fd进行轮循监听

  • int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask);

    添加了信号屏蔽集合,同时超时结构体也改变了

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

struct timespec {
    long    tv_sec;         /* seconds */
    long    tv_nsec;        /* nanoseconds */
};

使用流程

  • 第一步 socket通用流程,先绑定一个fd,做好服务器监听
int sockfd;
socklen_t len;
struct sockaddr_in my_addr;
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = PF_INET;
my_addr.sin_port = htons(myport);
//my_addr.sin_addr.s_addr = inet_addr(argv[1]);
my_addr.sin_addr.s_addr = INADDR_ANY;

bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr));
listen(sockfd, lisnum);
  • 第二步 对fd_set结构体进行设置
    注意!!!!!在select结束后,要重新监听时,一定要重新设置一遍,因为fd_set结构体内容已经改变
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
FD_SET(new_fd, &rfds);
  • 第三步 使用select轮循监听所有文件描述符
    注意!!!!!select第一个参数是所有文件描述符中最大的那个+1
//可以选择性的设置超时时间
struct timeval tv={20,0};
select(maxfd + 1, &rfds, NULL, NULL, &tv);
//如果不设置超时时间,直接设置为NULL就可以了

  • 第四步 处理监听的数据
if (FD_ISSET(new_fd, &rfds)) 
{
...//处理方法
...
}

demo

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/types.h>

#define MAXBUF 1024

int main(int argc, char **argv)
{
        int sockfd, new_fd;
        socklen_t len;
        struct sockaddr_in my_addr, their_addr;
        unsigned int myport, lisnum;
        char buf[MAXBUF + 1];
        fd_set rfds;
        struct timeval tv;
        int retval, maxfd = -1;

        if (argv[2])
                myport = atoi(argv[2]);
        else
                myport = 7838;
        if (argv[3])
                lisnum = atoi(argv[3]);
        else
                lisnum = 2;
        if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
                perror("socket");
                exit(EXIT_FAILURE);
        }

        bzero(&my_addr, sizeof(my_addr));
        my_addr.sin_family = PF_INET;
        my_addr.sin_port = htons(myport);
        if (argv[1])
            my_addr.sin_addr.s_addr = inet_addr(argv[1]);
        else
            my_addr.sin_addr.s_addr = INADDR_ANY;
        if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {
           perror("bind");
           exit(EXIT_FAILURE);
        }
         if (listen(sockfd, lisnum) == -1) {
            perror("listen");
            exit(EXIT_FAILURE);
         }

         while (1) 
		 {
           	printf ("\n----wait for new connect\n");
            len = sizeof(struct sockaddr);
            if ((new_fd =accept(sockfd, (struct sockaddr *) &their_addr,&len)) == -1) {
            	perror("accept");
             	exit(errno);
            } else
           		printf("server: got connection from %s, port %d, socket %d\n", 
						inet_ntoa(their_addr.sin_addr),ntohs(their_addr.sin_port), new_fd);
            while (1) 
			{
              	FD_ZERO(&rfds);
               	FD_SET(0, &rfds);
                FD_SET(new_fd, &rfds);
                maxfd = new_fd;
                tv.tv_sec = 1;
                tv.tv_usec = 0;
                retval = select(maxfd + 1, &rfds, NULL, NULL, &tv);
                if (retval == -1) 
				{
					perror("select");
					exit(EXIT_FAILURE);
				} else if (retval == 0) {
                 		continue;
                } 
				else
				{
                    if (FD_ISSET(0, &rfds))
					{
                         	bzero(buf, MAXBUF + 1);
                        	fgets(buf, MAXBUF, stdin);
                          	if (!strncasecmp(buf, "quit", 4)) {
                            	printf("i will quit!\n");
                             	break;
                          	}
                         	len = send(new_fd, buf, strlen(buf) - 1, 0);
                        	if (len > 0)
                               	printf ("send successful,%d byte send!\n",len);
                          	else {
                              	printf("send failure!");
                            	break;
                            }
					}
                    if (FD_ISSET(new_fd, &rfds)) 
					{ 
                           	bzero(buf, MAXBUF + 1);
                          	len = recv(new_fd, buf, MAXBUF, 0);
                           	if (len > 0)
                               	printf ("recv success :'%s',%dbyte recv\n", buf, len);
                           	else
							{
                             	if (len < 0)
                                	printf("recv failure\n");
                               	else
								{
                                  	printf("the ohter one end ,quit\n");
                                 	break;
								}
                           	}
           			}
                 }
			}
            close(new_fd);
            printf("need othe connecdt (no->quit)");
            fflush(stdout);
            bzero(buf, MAXBUF + 1);
            fgets(buf, MAXBUF, stdin);
            if (!strncasecmp(buf, "no", 2)) 
			{
                printf("quit!\n");
                break;
            }
        }
        close(sockfd);
        return 0;
}

  • 如需处理多个客户端,只需要做一个fd数组,循环判断即可

官方demo

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
	fd_set rfds;
	struct timeval tv;
	int retval;

	/* Watch stdin (fd 0) to see when it has input. */
	FD_ZERO(&rfds);
	FD_SET(0, &rfds);

	/* Wait up to five seconds. */
	tv.tv_sec = 5;
	tv.tv_usec = 0;

	retval = select(1, &rfds, NULL, NULL, &tv);
	/* Don't rely on the value of tv now! */

	if (retval == -1)
		perror("select()");
	else if (retval)
		printf("Data is available now.\n");
		/* FD_ISSET(0, &rfds) will be true. */
	else
		printf("No data within five seconds.\n");

	exit(EXIT_SUCCESS);
}