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

问题描述 投票:0回答:1

我正在 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++;
}
c server tcp timeout posix-select
1个回答
1
投票
select(server_fd + 1, & set, NULL, NULL, & timeout);

您的代码依赖于 select 修改您在循环外部设置的

timeout
,以便
timeout
反映剩余时间。但您不能依赖此行为,因为它仅特定于某些平台(例如 Linux)。

特别是在您的 MacOS 平台上,select 的手册页明确指出超时不会按照您所依赖的方式更改:

...为了进行民意调查,超时参数应该是 非零,指向零值 timeval 结构。

没有超时 由 select() 更改,并且可以在后续调用中重用,但是它是 在每次调用 select() 之前重新初始化它是一种很好的方式。

这意味着您必须自己计算在

select

 中花费的时间,并在再次调用 
timeout
 时相应地调整 
select

© www.soinside.com 2019 - 2024. All rights reserved.