케이피's 불량블로그!

블로그 이미지

케이피

OOP, Debugging... 인생의 숙제들..... [블로그의 글을 맹신하면 곤란]

How To Control Connection Timeout Value by Creating Second Thread

잡다한 정보들(기타정보) 2009. 5. 18. 22:27
View products that this article applies to.
This article was previously published under Q224318
Expand all | Collapse all

SUMMARY

This acticle shows a workaround to the InternetSetOption API bug on setting timeout values by creating a second thread.
InternetSetOption Does Not Set Timeout Values

MORE INFORMATION

The following sample code controls how long to wait while connecting to the FTP server in WinInet. It creates a worker thread to call the blocking WinInet APIs. If the connection takes more time than the specified timeout value, the original thread will call InternetCloseHandle to release the blocking WinInet function. For HTTP communications the same idea applies. In the case of HTTP, the actual connection occurs in the call to HttpSendRequest.
   #include <windows.h>
   #include <wininet.h>
   #include <iostream.h>

   DWORD WINAPI WorkerFunction( LPVOID ); 
   HINTERNET g_hOpen, g_hConnect;

   typedef struct 
   {
       CHAR* pHost;
       CHAR* pUser;
       CHAR* pPass;
   } PARM;

   void main()
   {
       CHAR    szHost[] = "localhost";
       CHAR    szUser[] = "JoeB";
       CHAR    szPass[] = "test";
       CHAR    szLocalFile[] = "localfile";
       CHAR    szRemoteFile[] = "remotefile";
       DWORD   dwExitCode;
       DWORD   dwTimeout;
       PARM    threadParm;

       g_hOpen = 0;
       if ( !( g_hOpen = InternetOpen ( "FTP sample", 
                                        LOCAL_INTERNET_ACCESS, 
                                        NULL, 
                                        0, 
                                        0 ) ) )
       {         
           cerr << "Error on InternetOpen: " << GetLastError() << endl;
           return ;
       }

       // Create a worker thread 
       HANDLE   hThread; 
       DWORD    dwThreadID;
       threadParm.pHost = szHost;
       threadParm.pUser = szUser;
       threadParm.pPass = szPass;

       hThread = CreateThread(
                     NULL,            // Pointer to thread security attributes 
                     0,               // Initial thread stack size, in bytes 
                     WorkerFunction,  // Pointer to thread function 
                     &threadParm,     // The argument for the new thread
                     0,               // Creation flags 
                     &dwThreadID      // Pointer to returned thread identifier 
                 );    

       // Wait for the call to InternetConnect in worker function to complete
       dwTimeout = 5000; // in milliseconds
       if ( WaitForSingleObject ( hThread, dwTimeout ) == WAIT_TIMEOUT )
       {
           cout << "Can not connect to server in " 
                << dwTimeout << " milliseconds" << endl;
           if ( g_hOpen )
   InternetCloseHandle ( g_hOpen );
           // Wait until the worker thread exits
           WaitForSingleObject ( hThread, INFINITE );
           cout << "Thread has exited" << endl;
           return ;
       }
    
       // The state of the specified object (thread) is signaled
       dwExitCode = 0;
       if ( !GetExitCodeThread( hThread, &dwExitCode ) )
       {
           cerr << "Error on GetExitCodeThread: " << GetLastError() << endl;
           return ;
       }

       CloseHandle (hThread);
       if ( dwExitCode )
       // Worker function failed
          return ;
    
       if ( !FtpGetFile ( g_hConnect, 
                          szRemoteFile,
                          szLocalFile,
                          FALSE,INTERNET_FLAG_RELOAD, 
                          FTP_TRANSFER_TYPE_ASCII,
                          0 ) )
       {
           cerr << "Error on FtpGetFile: " << GetLastError() << endl;
           return ;
       }

       if ( g_hConnect )
           InternetCloseHandle( g_hConnect );
       if ( g_hOpen )
           InternetCloseHandle( g_hOpen );

       return ;
   }

   /////////////////// WorkerFunction ////////////////////// 
   DWORD WINAPI 
   WorkerFunction(
       IN LPVOID vThreadParm
   )
   /*
   Purpose:
       Call InternetConnect to establish a FTP session  
   Arguments:
       vThreadParm - points to PARM passed to thread
   Returns:
       returns 0  
   */ 
   {
       PARM* pThreadParm;
       // Initialize local pointer to void pointer passed to thread
       pThreadParm = (PARM*)vThreadParm;
       g_hConnect = 0;
    
       if ( !( g_hConnect = InternetConnect (
                                g_hOpen, 
                                pThreadParm->pHost,
                                INTERNET_INVALID_PORT_NUMBER,
                                pThreadParm->pUser,
pThreadParm->pPass,
                                INTERNET_SERVICE_FTP, 
                                0,
                                0 ) ) )
       {
           cerr << "Error on InternetConnnect: " << GetLastError() << endl;
           return 1; // failure
       }
       
       return 0;  // success
   }
				


이런...망할 MFC!!!
Posted by 케이피
블로그 이미지

OOP, Debugging... 인생의 숙제들..... [블로그의 글을 맹신하면 곤란]

by 케이피

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • 유로2008 일정
  • Emma Stone
  • 객체지향
  • debugging
  • dbgView
  • 엠마스톤
  • trace
  • 8강전
  • IME
  • c#
  • CString
  • Mentor
  • 최강 볼걸
  • MFC
  • DLL
  • SmartClient
  • 최적화?
  • Automation
  • XML
  • CView
  • JAVA 맛보기
  • 안드로이드
  • vs2008
  • MFC Tip
  • OOP
  • excel
  • LPCSTR
  • CNN
  • activex
  • bug

글 보관함

«   2025/06   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

링크

카테고리

전체보기 (98)
Qt의 오묘함 (1)
영양가없는이야기(개인사) (1)
주체못할파괴본능(디버그) (5)
넌왜C++을C처럼쓰냐?(OOP) (2)
잡다한 정보들(기타정보) (53)
귀찮아...(유용링크) (13)
참 잼난다(취미) (6)
JAVA 의 향기~(자바) (2)
코딩을부탁해(Rapid Coding) (0)
베스트똘추짓(개고생리스트) (11)
매운핫소스(허접소스) (1)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
케이피's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

케이피's 불량블로그!

OOP, Debugging... 인생의 숙제들..... [블로그의 글을 맹신하면 곤란]

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • 전체보기 (98)
    • Qt의 오묘함 (1)
    • 영양가없는이야기(개인사) (1)
    • 주체못할파괴본능(디버그) (5)
    • 넌왜C++을C처럼쓰냐?(OOP) (2)
    • 잡다한 정보들(기타정보) (53)
    • 귀찮아...(유용링크) (13)
    • 참 잼난다(취미) (6)
    • JAVA 의 향기~(자바) (2)
    • 코딩을부탁해(Rapid Coding) (0)
    • 베스트똘추짓(개고생리스트) (11)
    • 매운핫소스(허접소스) (1)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바