gpt4 book ai didi

c - 限制与服务器不工作的最大连接数

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:31 25 4
gpt4 key购买 nike

我已经使用 C 套接字编程构建了一个客户端-服务器程序,并且它在我的 Ubuntu OS 上完美运行,而 Ubuntu OS 在 VMware 上运行。我唯一的问题是 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

}

}

}

为什么会这样

最佳答案

Though i have set the connection limit to 2

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

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.

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

关于c - 限制与服务器不工作的最大连接数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com