c - 如何在接受多个客户端连接时设置 TCP 服务器超时

标签 c select tcp server timeout

我正在 TCP 服务器中开发一个函数,该函数在定义的时间段内接受预定数量的客户端连接(我现在将其设置为 10 秒),并在达到预定连接数时返回。我正在使用 select 函数使服务器超时,但由于某种原因,每次客户端加入时超时都会重置。例如,如果客户端在 5 秒后加入服务器,则超时将重置并从 10 开始再次倒计时。非常感谢您的帮助,谢谢。

我使用的是 mac,我认为在这个操作系统上 FD_ISSET 用于检查客户端是否已连接(我很确定 Linux 上不需要)。因此,您可以像处理 Linux 上 select 函数的返回值一样处理该函数的返回值。

while (num_conn < NO_OF_CLIENTS) {

    // Listen for clients
    err = listen(server_fd, 128);
    if (err < 0) {
        fprintf(stderr, "Could not listen on socket\n");
        exit(EXIT_FAILURE);
    }
    // Zero out memory for the client information
    memset( & client, 0, sizeof(client));

    socklen_t client_len = sizeof(client);
    FD_ZERO( & set);
    FD_SET(server_fd, & set);

    select(server_fd + 1, & set, NULL, NULL, & timeout);

    // server times out after allowing 30 seconds for clients to join.
    // If no clients join function returns 0. Otherwise returns no_clients
    nready = FD_ISSET(server_fd, & set);
    printf("nready is: %d\n", nready);

    if (nready == 0) {
        return num_conn; // returns number of connections if a time out occurs. 
    }

    // Accept the connection from the client
    client_fd[num_conn] = accept(server_fd, (struct sockaddr * ) & client, & client_len);
    if (client_fd < 0) {
        fprintf(stderr, "Could not establish new connection\n");
        // SEND REJECT??
        exit(EXIT_FAILURE);
    }

    // Assign value to number of clients here and let it set after a time out
    // more work to  be done here
    printf("Accepted connection from client %d\n", num_conn);
    num_conn++;
}

最佳答案

select(server_fd + 1, & set, NULL, NULL, & timeout);

您的代码依赖于选择修改您在循环外部设置的timeout,以便timeout反射(reflect)剩余时间。但您不能依赖此行为,因为它仅特定于某些平台(例如 Linux)。

特别是在您的 MacOS 平台上 man page of select明确指出超时并没有按照你依赖的方式改变:

... To effect a poll, the timeout argument should be non-nil, pointing to a zero-valued timeval structure. Timeout is not changed by select(), and may be reused on subsequent calls, however it is good style to re-initialize it before each invocation of select().

这意味着您必须自己计算出在 select 中花费的时间,并在再次调用 select 时相应地调整超时

关于c - 如何在接受多个客户端连接时设置 TCP 服务器超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56196515/

相关文章:

c - 将匿名 PIPE HANDLE 传递给子进程

mysql - SQL 求和和分组

linux - TCP_NEW_SYN_RECV 是什么意思?

google-app-engine - 如何在 golang 中在 google appengine 上构建 TCP 监听器或服务器?

jquery - jQuery 每个函数迭代选择的问题

go - 给定一个TCP服务器,如何获取连接域地址

C gethostbyaddr 返回 NULL

C、如何将数组中的数字拆分为 int

C - 从数组中删除重复项并将这些重复项存储在另一个数组中

mysql - 如何在其他带有 LEFT JOIN 的 SELECT 查询中包含 SELECT 查询