限制与服务器的最大连接数不起作用

Com*_*erd 1 c sockets posix

我使用 C 套接字编程构建了一个客户端-服务器程序,它在我的 Ubuntu 操作系统上完美运行,该操作系统在 VMware 上运行。我唯一的问题是API 调用。

虽然我将连接限制设置为 2,但我可以同时打开四个终端并连接到服务器。

 listen (serverFd, 2); /* Maximum pending connection length */
Run Code Online (Sandbox Code Playgroud)

客户端和服务器运行在同一台计算机上。

这是代码片段

#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>       /* for sockaddr_un struct */
#define DEFAULT_PROTOCOL   0
#define BUFFER_SIZE 1024


/* POSIX renames "Unix domain" as "local IPC."
    Not all systems define AF_LOCAL and PF_LOCAL (yet). */
#ifndef AF_LOCAL
#define AF_LOCAL    AF_UNIX
#endif
#ifndef PF_LOCAL
#define PF_LOCAL    PF_UNIX
#endif


/****************************************************************/
main ()
{

    printf("Hello, server is starting...\n");

    // initialize data from text file into system
    readData();

    printf("Country data loaded with total of %i countries available.\n", NoOfRecordsRead);

    if(NoOfRecordsRead == 0)
    {
        printf("No valid data to serve, terminating application...\n");
        exit (-1);
    }

    int serverFd, clientFd, serverLen, clientLen;
    struct sockaddr_un serverAddress;/* Server address */
    struct sockaddr_un clientAddress; /* Client address */
    struct sockaddr* serverSockAddrPtr; /* Ptr to server address */
    struct sockaddr* clientSockAddrPtr; /* Ptr to client address */

    /* Ignore death-of-child signals to prevent zombies */
    signal (SIGCHLD, SIG_IGN);

    serverSockAddrPtr = (struct sockaddr*) &serverAddress;
    serverLen = sizeof (serverAddress);

    clientSockAddrPtr = (struct sockaddr*) &clientAddress;
    clientLen = sizeof (clientAddress);

    /* Create a socket, bidirectional, default protocol */
    serverFd = socket (AF_LOCAL, SOCK_STREAM, DEFAULT_PROTOCOL);
    serverAddress.sun_family = AF_LOCAL; /* Set domain type */
    strcpy (serverAddress.sun_path, "country"); /* Set name */
    unlink ("country"); /* Remove file if it already exists */
    bind (serverFd, serverSockAddrPtr, serverLen); /* Create file */
    listen (serverFd, 2); /* Maximum pending connection length */

    printf("Server started.\n");

    while (1) /* Loop forever */
    {
        /* Accept a client connection */
        clientFd = accept (serverFd, clientSockAddrPtr, &clientLen);

        if (fork () == 0) /* Create child to send recipe */
        {
                 //do something

        }

    }

}   
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况

Bra*_*ncy 5

虽然我已将连接限制设置为 2

不。您已将 listen backlog设置为 2。阅读有关 listen 命令的文档:

backlog 参数定义了 sockfd 的挂起连接队列可以增长到的最大长度。如果连接请求在队列已满时到达,客户端可能会收到一个带有 ECONNREFUSED 指示的错误,或者,如果底层协议支持重传,则该请求可能会被忽略,以便稍后重新尝试连接成功。

accept()如果您想限制同时连接的数量,您的程序可以决定不调用。