我有一个代码,服务器向客户端发送包含TCP端口号的UDP消息。然后,服务器等待与客户端的传入TCP连接。但是,select()函数返回多个连接的超时。我可以弄清楚可能是什么问题。
非常感谢对以下代码的任何帮助和评论。在此先感谢您的帮助。
void initialise( void )
{
m_tcp_listensocket = getlistensocket();
highsock = m_tcp_listensocket;
setnonblocking(m_tcp_listensocket);
struct timeval timeout;
timeout.tv_sec = m_timeout;
timeout.tv_usec = 0;
// Send UDP messages to clients not connected
for (int i = 0; i < UDP_Connections.size(); i++)
{
// Only to clients not connected
if ( TCP_Connections[i]->IsConnected() )
{
continue;
}
// making the message: 'server_address:server_port'.
char l_str_server_port_number[6];
sprintf ( l_str_server_port_number, "%d", TCP_Connections[i]->get_server_port_number ());
struct hostent *host;
if( (host = gethostbyname( m_host_name )) == NULL)
{
// gethostbyname() made error
}
struct in_addr MyAddress;
memcpy( &MyAddress.s_addr, host->h_addr_list[0], sizeof( MyAddress.s_addr ) );
std::string l_str_init_message = std::string(l_str_server_port_number) + "\0";
UDP_Connections[i]->sendUDPMessage(l_str_init_message.c_str());
}
for (int i = 0; i < TCP_Connections.size(); i++)
{
struct sockaddr_in clientaddr;
bzero(&clientaddr, sizeof(clientaddr));
clientaddr.sin_family = AF_INET;
clientaddr.sin_addr.s_addr = htonl(INADDR_ANY);
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(m_tcp_listensocket, &readSet);
int readsocks = select(highsock+1, &readSet, NULL, NULL, &timeout);
switch (readsocks)
{
case 0:
/* timeout */
break;
case -1:
/* error */
break;
default:
if (FD_ISSET (m_tcp_listensocket, &readSet))
{
socklen_t tempo = (socklen_t)sizeof(clientaddr);
int l_Socket = accept(m_tcp_listensocket, (struct sockaddr *)&clientaddr, &tempo);
if ( l_Socket > highsock )
highsock = l_Socket;
if ( l_Socket >= 0 )
{
// connection accepted
char adr[16] ;
inet_ntop(PF_INET,&clientaddr.sin_addr, adr, sizeof(adr));
for (int j= 0; j < UDP_Connections.size(); j++)
{
if ( UDP_Connections[j]->get_clientIP() == (std::string)adr )
{
TCP_Connections[j]->set_TCPsocket( l_Socket );
break;
}
}
}
else
{
// socket error
}
}
}
}
}
答案 0 :(得分:3)
select()
的某些实现更新了它们的超时参数,您可能需要在每次调用之前重置它。