Where The Streets Have No Name

CSocket 과 CAsyncSocket에서 Thread문제 본문

Developement/C, C++, C#

CSocket 과 CAsyncSocket에서 Thread문제

highheat 2009. 5. 26. 20:14

출처:http://www.debuglab.com/knowledge/csocket.html
       http://microsoft.ease.lsoft.com/scripts/wa-msn.exe?A2=ind9811c&L=mfc&T=0&P=5460

1.요약 

CSocket / CAsyncSocket을 생성한 곳이 아닌 다른 Thread로 넘겨 처리할 경우 CSocket이 가진 Thread state가 변해 에러가 발생합니다. 

예를들어 한쪽에서는 Listen을 하여 클라이언트 Socket을 Accept하고, Thread를 생성시켜 Socket전송을 맡길 경우에 Thread문제를 해결하는 방법을 소개하겠습니다. 


2.본문 

방법은 간단합니다. 
Accept한 Socket을 Deatch시키고 거기에서 나온 handle을 Thread로 넘김니다. 
그리고 Thread에서 handle을 Attach시켜 CSocket / CAsyncSocket 개체 인스턴스를 만들어 사용하면 됩니다. 

void OnAccept(int nError)
{
  // create the new socket
  CSocket *pSock = new CSocket();
  SOCKET tempSock = pSock->Detach();
  // pass a pointer to the SOCKET object to the thread function
  CWinThread *pThread = AfxBeginThread(ThreadFunc, &tempSock)
}

// Worker thread function
UINT ThreadFunc(LPVOID lpVoid)
{
  // If you use a worker thread, you'll need to
  // call AfxSocketInit()...
  if (AfxSocketInit() == FALSE)
  {
    TRACE( "AfxSocketInit() failed!\n" );
    return 1;
  }
  SOCKET *pSocket = (SOCKET *)lpVoid;
  CSocket *pSocket = new CSocket();
  pSocket->Attach(*pSocket)
}