限制服务器无法连接的最大连接数

时间:2014-02-17 04:39:06

标签: c sockets posix

我已经使用C套接字编程构建了一个客户端 - 服务器程序,并且它在我的运行在VMware上的Ubuntu OS上完美运行。我遇到的唯一问题是使用listen API调用。

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

 listen (serverFd, 2); /* Maximum pending connection length */

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

这是代码的片段

#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

        }

    }

}   

为什么会发生这种情况

1 个答案:

答案 0 :(得分:4)

  

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

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

  

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

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