How to set a socket connection timeout


#include <windows.h>#include <stdio.h>#include <conio.h>int main(void)
{
   COMMTIMEOUTS timeouts;
   HANDLE handle;
   DCB dcb;   char buffer[1000] = "abcdefghijklmnopqrstuvwxyz";
   DWORD dwLen;

   handle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE,               0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);   if (handle == INVALID_HANDLE_VALUE)
   {
      printf("CreateFile() Failed
");      return 1;    }   timeouts.ReadIntervalTimeout        = 300;   timeouts.ReadTotalTimeoutMultiplier = 0;   timeouts.ReadTotalTimeoutConstant   = 0;   timeouts.WriteTotalTimeoutMultiplier= 0;   timeouts.WriteTotalTimeoutConstant  = 0;   if (!SetCommTimeouts(handle, &timeouts))    {       printf("SetCommTimeouts() Failed
");      return 2;    }    ZeroMemory(&dcb, sizeof(dcb));    dcb.DCBlength           = sizeof(dcb);    dcb.BaudRate            = 19200;     dcb.fParity             = TRUE;    dcb.fOutxCtsFlow        = false;    dcb.fOutxDsrFlow        = false;    dcb.fDtrControl         = DTR_CONTROL_ENABLE;    dcb.fDsrSensitivity     = FALSE;    dcb.fTXContinueOnXoff   = FALSE;    dcb.fOutX               = false;    dcb.fInX                = false;    dcb.fNull               = FALSE;    dcb.fRtsControl         = RTS_CONTROL_ENABLE;    dcb.fAbortOnError       = false;    dcb.ByteSize            = 8;    dcb.Parity              = ODDPARITY;    dcb.StopBits            = ONESTOPBIT;   if (!SetCommState(handle, &dcb))    {       printf("SetCommState() Failed
");      return 1;    }   while (! _kbhit() )    {       printf("W");      if (!WriteFile(handle, buffer, 40, &dwLen, 0))          printf("\rWriteFile() returned %d
", GetLastError());       printf("R");      if ( !ReadFile(handle, buffer, 100, &dwLen, 0) )          printf("\rReadFile() returned %d
", GetLastError());    }    printf("
Done!
");    CloseHandle(handle);   return 0; }