《Linux網路開發必學教程》5_基於多路複用的服務端

TianSong發表於2022-05-03

問題:使用 select() 函式可以擴充套件服務端功能嗎? 如果可以,具體怎麼實現?


目前服務端的瓶頸分析

服務端大多數時候處於等待狀態,無法發揮主機(裝置)的最大效能

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);
}

解決方案:阻塞變輪詢

  • 通過 select() 函式首先監聽服務端 server_fd, 目標事件為 “連線”(讀)
  • 當事件發生(客戶端連線),則呼叫 accept() 接受連線
  • 將 client_fd 加入監聽範圍,目標事件為“資料接收”(讀)
  • 迴圈檢視各個被監聽的檔案描述符是否有事件發生
實現方式

image.png

實現邏輯

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)
                }
            }
        }
    }
}

實現關鍵

  • 動態調整需要監視的檔案描述符

    • 當接收到客戶端連線時,將客戶端檔案描述符加入監聽變數 (fd_set) 中
    • 當發現客戶端斷開時,在監聽變數 (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);
}
  • 動態調整需要監視的檔案描述符數量
  • 保證每個需要監視的檔案描述符能夠被輪詢
  • max = (client > max) ? client : max

程式設計實驗:改進後的服務端

#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;
}

思考:改進後的服務端是否還有優化的空間? select() 是 Linux() 系統特有的嗎?

相關文章