Question: Can the server-side functionality be extended by using the select() function? If so, how?


Bottleneck analysis of the current server

The server is in a waiting state most of the time and cannot exert the maximum performance of the host (device).

 while (1) {
    // 阻塞,等待客户端连接
    client = accept(server, (struct sockaddr*)&caddr, &asize);

    printf("client: %d\n", client);

    do {
        // 阻塞,等待客户端数据
        r = recv(client, buf, sizeof(buf), 0);
        if (r > 0) {
            printf("Receive: %s\n", buf);

            if (strcmp(buf, "quit") != 0) {
                len = send(client, buf, r, 0);
            }
            else {
                break;
            }
        } 
    } while (r > 0);

    close(client);
}

Solution: Blocking Variable Polling

  • First listen to the server server_fd through the select() function, and the target event is "connection" (read)
  • When an event occurs (client connection), call accept() to accept the connection
  • Add client_fd to the listening scope, and the target event is "data reception" (read)
  • Loop to see if there is an event on each monitored file descriptor
Method to realize

image.png

implement logic

 while (1) {
    rset = reads;

    num = select(max + 1, &rset, 0, 0, &timeout);

    if (num > 0) {
        int i = 0;
        for (i=1; i<=max; ++i) {  // 注意, 0 被命令行占用,下标从 1 开始遍历
            if (FD_ISSET(i, &rset)) {
                if (i == server) {
                    // accept and add client to fd_set
                } else {
                    // read data from client by i (fd)
                }
            }
        }
    }
}

realization key

  • Dynamically adjust the file descriptors that need to be monitored

    • When a client connection is received, add the client file descriptor to the listening variable (fd_set)
    • When it is found that the client is disconnected, the client file descriptor is removed from the listening variable (fd_set)
 // 添加监听
if (client > -1) {
    FD_SET(client, &reads);
    max = (client > max) ? client : max;
    printf("client: %d\n", client);
}

// 剔除监听
if (r == -1) {
    FD_CLR(i, &reads);
    close(i);
}
  • Dynamically adjust the number of file descriptors to monitor
  • Ensure that each file descriptor to be monitored can be polled
  • max = (client > max) ? client : max

Programming Experiment: Improved Server

 #include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int server_handler (int server)
{
    struct sockaddr_in addr = {0};
    socklen_t asize = sizeof(addr);

    return accept(server, (struct sockaddr*)&addr, &asize);
}

int client_handler(int client)
{
    char buf[32] = {0};
    int ret = read(client, buf, sizeof(buf) - 1);

    if (ret > 0) {
        buf[ret] = 0;

        printf("Receive: %s\n", buf);

        if (strcmp(buf, "quit") != 0) {
            ret = write(client, buf, ret);
        } else {
            return -1;
        }
    }

    return ret;
}

int main()
{
    int server = 0;
    struct sockaddr_in saddr = {0};
    int max = 0;
    int num = 0;
    fd_set reads = {0};
    fd_set temps = {0};
    struct timeval timeout = {0};

    server = socket(PF_INET, SOCK_STREAM, 0);

    if (server == -1) {
        printf("server socket error\n");
        return -1;
    }

    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = htons(8888);

    if (bind(server, (struct sockaddr*)&saddr, sizeof(saddr)) == -1) {
        printf("server bind error\n");
        return -1;
    }

    if (listen(server, 1) == -1) {
        printf("server listen error\n");
        return -1;
    }

    printf("server start success\n");

    FD_ZERO(&reads);
    FD_SET(server, &reads);

    max = server;

    while (1) {
        temps = reads;

        timeout.tv_sec = 0;
        timeout.tv_usec = 10000;

        num = select(max+1, &temps, 0, 0, &timeout);

        if (num > 0) {
            int i = 0;

            for (i=1; i<=max; ++i) {
                if (FD_ISSET(i, &temps)) {
                    if (i == server) {
                        int client = server_handler(server);

                        if (client > -1) {
                            FD_SET(client, &reads);

                            max = (client > max) ? client : max;

                            printf("accept client: %d\n", client);
                        }
                    }
                    else {
                        int r = client_handler(i);

                        if (r == -1) {
                            FD_CLR(i, &reads);

                            close(i);
                        }
                    }
                }
            }
        }
    }

    return 0;
}

Thinking: Is there still room for optimization in the improved server? Is select() specific to the Linux() system?

TianSong
734 声望138 粉丝

阿里山神木的种子在3000年前已经埋下,今天不过是看到当年注定的结果,为了未来的自己,今天就埋下一颗好种子吧