1
我有一個代碼,其中服務器發送一個UDP消息,其中包含一個TCP端口號給客戶端。然後服務器等待與客戶端的傳入TCP連接。但是,select()函數返回多個連接的超時值。我可以弄清楚可能是什麼問題。C++ socket select()函數返回0與許多連接
對以下代碼的任何幫助和意見都非常感謝。預先感謝您的幫助。
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
}
}
}
}
}
謝謝你的回答。這是需要注意的一點,但它不能解決問題。當許多客戶端嘗試建立TCP連接時,select()會返回超時值。 – user609823 2011-02-14 20:55:47