我编写了一个服务器代码,它接受新客户端和来自客户端的数据。但问题是,尽管没有来自客户端的数据,但 select 并没有等到超时。我想等待 5 秒并向可用的客户端发送心跳。但它在第一次迭代中等待 5 秒,然后在下一次迭代中快速发送心跳。如何解决这个问题呢。提前致谢。
void * Communicate(void * id)
{
int *iSockID = (int *) id;
int listener = *iSockID;
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select() read
fd_set write_fds; // temp file descriptor list for select() read
int fdmax; // maximum file descriptor number
int i, j, rv;
FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
// add the listener to the master set
FD_SET(listener, &master);
printf("Listener is %d \n" , listener);
// keep track of the biggest file descriptor
fdmax = listener; // so far, it's this one
//accept 3 clients
// main loop
for(;;) {
read_fds = master; // copy it
write_fds = master;
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
int iResult = select(fdmax+1, &read_fds, &write_fds, NULL, &tv) ;
if (iResult == -1)
{
perror("select");
exit(4);
}
for(i = 0; i <= fdmax; i++)
{
//send work for clients
SendHeartBeats(write_fds , fdmax , listener , i );
}
// run through the existing connections looking for data to read
// ADD NEW CONNECTIONS READ FROM CONNECTIONS
for(i = 0; i <= fdmax; i++)
{
if (FD_ISSET(i, &read_fds))
{ // we got one!!
// handle new connections
if (i == listener)
{
AcceptNewClients(master , fdmax , listener );
} else
{
AccepeDataFromClients(i , master);
} // END handle data from client
} // END got new incoming connection
} // END looping through file descriptors
sleep(3);
} // END for(;;)
return 0;
}
最佳答案
您不能通过 equals 来 fd_set 变量。您需要使用FD_COPY。如果不这样做,您只需复制实际数据的句柄,该数据已标记为已完成。
关于c++ - select 不等待 C++ 套接字中的超时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14496204/