我尝试编写接受请求的Windows服务器应用程序。我希望使用select()
函数来接收新的连接和请求-监视侦听套接字和以前建立的连接。
问题是FD_ISSET 总是返回0。这是代码。你能指出我的错误吗?
WORD wVersionRequested;
WSADATA wsaData;
int iResult;
// Initializing WSA
wVersionRequested = MAKEWORD( 2, 2 );
iResult = WSAStartup( wVersionRequested, &wsaData );
if ( iResult != 0 )
{
std::cout << "WSAStartup failed with error: " << WSAGetLastError() << std::endl;
return false;
}
if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup();
std::cout << "Could not find a usable version of Winsock.dll" << std::endl;
return false;
}
int iResult;
struct addrinfo *result = NULL;
struct addrinfo hints;
std::stringstream ss;
ss << DEFAULT_PORT;
memset( &hints, 0, sizeof( hints ) );
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo( NULL, ss.str().c_str(), &hints, &result );
if ( iResult != 0 )
{
std::cout << "getaddrinfo() failed with error: " << WSAGetLastError() << std::endl;
return false;
}
// Create a SOCKET for connecting to server
m_listenSocket = socket( result->ai_family, result->ai_socktype, result->ai_protocol );
if ( m_listenSocket == INVALID_SOCKET )
{
std::cout << "socket() failed with error: " << WSAGetLastError() << std::endl;
return false;
}
// Setup the TCP listening socket
iResult = bind( m_listenSocket, result->ai_addr, ( int ) result->ai_addrlen );
if ( iResult == SOCKET_ERROR )
{
std::cout << "bind() failed with error: " << WSAGetLastError() << std::endl;
freeaddrinfo( result );
return false;
}
freeaddrinfo( result );
// Listen for the TCP listening socket
if ( listen( m_listenSocket, SOMAXCONN ) == SOCKET_ERROR )
{
std::cout << "listen() failed with error: " << WSAGetLastError() << std::endl;
return false;
}
fd_set active_fd_set;
fd_set read_fd_set;
// Initialize the set of active sockets.
FD_ZERO( &active_fd_set );
FD_SET( m_listenSocket, &active_fd_set );
while ( !m_forceStopMessages )
{
read_fd_set = active_fd_set;
int retVal = select( FD_SETSIZE, &read_fd_set, NULL, NULL, NULL );
if ( retVal < 0 )
{
std::cout << "select() failed with error: " << WSAGetLastError() << std::endl;
}
int readySockets = ( FD_SETSIZE < retVal ) ? FD_SETSIZE : retVal;
// Service all the sockets with input pending.
for ( int i = 0; i < readySockets; ++i )
{
if ( FD_ISSET( i, &read_fd_set ) )
{
if ( i == m_listenSocket )
{
// Accept a client socket
FD_SET( clientSocket, &active_fd_set );
}
else
{
/* Data arriving on an already-connected socket. */
FD_CLR( i, &active_fd_set );
}
}
}
}
答案 0 :(得分:1)
FD_ISSET
将套接字句柄作为第一个参数,而不是索引。