Andy,
A simple select() loop will solve that for you. Put a timeout on the select(), then do the recv(). If the recv() returns a 0 or -1, then the port is closed.
Here is a basic select loop template. Run something like this on its own thread and then have something to do your shutdown if it ever breaks the loop.
<pre>
for( ; ; )
{
// Wait 10 ms for data
fd_set read_set;
struct timeval wait;
wait.tv_sec = 0;
wait.tv_usec = 10*1000;
FD_ZERO(&read_set);
// Look either for Capture or Listen sockets
if( m_sockCapture != INVALID_SOCKET )
FD_SET(m_sockCapture, &read_set);
FD_SET(m_sockListen, &read_set);
int res = select(FD_SETSIZE, &read_set, NULL, NULL, &wait);
// Got some data
if( res > 0 )
{
// Listen socket activated
if( FD_ISSET(m_sockListen, &read_set) )
{
// Close old capture socket
//FD_CLR(pPM->m_sockCapture, &read_set);
if( m_sockCapture != INVALID_SOCKET && m_sockCapture )
closesocket(m_sockCapture);
// Accept the new Capture socket
struct sockaddr from;
int nFrom = sizeof(from);
m_sockCapture = accept(m_sockListen, &from, &nFrom);
if( m_sockCapture == INVALID_SOCKET || m_sockCapture < 0 )
{
m_sockCapture = INVALID_SOCKET;
return true;
}
}
// Capture socket activated
else if( FD_ISSET(m_sockCapture, &read_set) )
{
// Get the data
int nSize = recv(m_sockCapture, (char *)&m_Buffer[m_nBuffer], sizeof(m_Buffer)-m_nBuffer, 0);
if( nSize > 0 )
{
nSize += m_nBuffer;
// Process the data
m_nBuffer = ProcessData(m_Buffer, nSize);
}
else if( nSize <= 0 )
{
// Remote Disconnect
return true;
}
}
}
else if( res < 0 )
{
// Select error
return true;
}
else if( res == 0 )
{
// select timeout
}
}
</pre>