Multithreaded winsock
I have a multithreaded winsock application which works most of the time. The
problem I have is that in a wireless environment I can't depend on a good
connect. I have written some code to recover from the socket when the server
disappears and it seems to work. The issue I see is that the recv thread
refuses to let go of processing control when the socket disappears. Thus none
of the other threads can run until the socket becomes accessible again. Any
ideas ?
Randy
The socket is originally created before the thread starts.
unsigned __stdcall Network_in_ThreadFunc( void* pArguments )
{
int byte_count = 0;
int result = 0;
int iResult = 0;
unsigned char * local_ptr = 0;
long last_time = 0, current_time = 0;
long duration;
unsigned char data_in[NETWORK_IN_BUFFER_LENGTH];
log_str("Beginning of thread: Network_in_ThreadFunc\n"); // Write to the
log file
//printf("Waiting for Network data to intput.\n");
do {
ResetEvent(hReadEvents[6]);
printf("Network in thread.\n");
if(test_threads)
{
continue;
}
if(exiting) // For checking an exit situation inside a loop
{
//log_str("Leaving the Network in locale.\n"); // Write to the log file
_endthreadex( 98 );
}
/* Check to see if there is anything to do */
//byte_count = recv(ConnectSocket, (char *)&c_RadioInFIFO[0],
NETWORK_IN_BUFFER_LENGTH, 0);
byte_count = recv(ConnectSocket, (char *)&data_in[0],
NETWORK_IN_BUFFER_LENGTH, 0);
current_time = get_ms();
duration = current_time - last_time;
if((duration > 21000) && (last_time)) // about three minutes
{
last_time = 0;
printf("Network error: %d\n", WSAGetLastError());
printf("Network in socket timed out. Reseting !\n");
shutdown_wsocket(ConnectSocket);
ConnectSocket = (SOCKET)setup_networking(&iResult);
}
if(byte_count > 0)
{
last_time = current_time;
//local_packet = messege_manager(PM_NEW_PACKET, 0, 0, byte_count, NULL);
// display_messege_array(&messege_array[0]);
//local_ptr = chk_for_ACK_NAK((char *)&c_RadioInFIFO[0], byte_count,
&messege_array[0], &result);
local_ptr = chk_for_ACK_NAK((char *)&data_in[0], byte_count,
&messege_array[0], &result);
if(result == -2)
{
SetEvent(hReadEvents[THREAD_3]); // process the packets
continue; // max packets reached
}
printf("ACK/NAK result: %d\n", result);
//if(result == 2) // NAK
//{
// continue; // NAKs are handled by messege_manager
//}
//memcpy(&local_ptr[0], &c_RadioInFIFO[0], byte_count);
memcpy(&local_ptr[0], &data_in[0], byte_count);
set_messege(&messege_array[0], CORE_PROCESSOR,
CORE_NETWORK_PROCESSING, (unsigned char *)&local_ptr[0], byte_count, NULL,
false );
//printf("New network packet. Byte_count %d !\n",byte_count); // not
ack or nak
}
else
{
if(byte_count == -1)
{
//printf("Network error: %d\n", WSAGetLastError());
printf("Network in socket reset !\n");
//shutdown_wsocket(ConnectSocket);
ConnectSocket = (SOCKET)setup_networking(&iResult);
}
//printf("recv failed: %d\n", WSAGetLastError());
}
}while(TRUE);
_endthreadex( 98 );
return 98;
}