0
我已經構建了一個使用C套接字編程的客戶端服務器程序,並且可以在運行在VMware上的Ubuntu操作系統上完美運行。我遇到的唯一問題是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此平臺可以靜靜地將積壓值調低或更多地調高。 – EJP