这是我接受客户的单线程迭代代码:
static int msock = -1;
static volatile bool listenerRunning = true;
static void
ServerListenerLoop(void)
while (listenerRunning) {
int ssock;
struct sockaddr_storage cliAddr;
socklen_t cliAddrLen = sizeof cliAddr;
ssock = accept(msock, (struct sockaddr *)&cliAddr, &cliAddrLen);
if (ValidateClientSocket(ssock)) {
Server(ssock);
}
}
}
我使用select函数修改代码如下,以便任意数量的客户端可以同时连接服务器并与服务器交互(不工作):
static void
ServerListenerLoop(void)
{
struct sockaddr_in fsin; /* the from address of a client */
int msock; /* master server socket */
fd_set rfds; /* read file descriptor set */
fd_set fds; /* active file descriptor set */
int fd, nfds;
nfds = getdtablesize();
FD_ZERO(&afds);
FD_SET(msock, &afds);
while (listenerRunning) {
memcpy(&rfds, &afds, sizeof(rfds));
if (select(nfds, &rfds, (fd_set *)0, (fd_set *)0,
(struct timeval *)0) < 0)
errexit("select: %s\n", strerror(errno));
if (FD_ISSET(msock, &rfds)) {
int ssock;
struct sockaddr_storage cliAddr;
socklen_t cliAddrLen = sizeof cliAddr;
ssock = accept(msock, (struct sockaddr *)&cliAddr, &cliAddrLen);
if (ssock < 0)
errexit("accept: %s\n", strerror(errno));
FD_SET(ssock, &afds);
}
for (fd=0; fd<nfds; ++fd)
if (fd != msock && FD_ISSET(fd, &rfds)) {
(void) close(ssock);
FD_CLR(fd, &afds);
}
if (ValidateClientSocket(ssock)) { /*VALIDATES THE CLIENT SOCKET*/
Server(ssock);
}
}
}
请指导我解决我的问题