1.요약
CSocket / CAsyncSocket을 생성한 곳이 아닌 다른 Thread로 넘겨 처리할 경우 CSocket이 가진
Thread state가 변해 에러가 발생합니다.
예를들어 한쪽에서는 Listen을 하여 클라이언트 Socket을
Accept하고, Thread를 생성시켜 Socket전송을 맡길 경우에 Thread문제를 해결하는 방법을 소개하겠습니다.
2.본문
방법은 간단합니다.
Accept한 Socket을 Deatch시키고 거기에서 나온
handle을 Thread로 넘김니다.
그리고 Thread에서 handle을 Attach시켜 CSocket / CAsyncSocket
개체 인스턴스를 만들어 사용하면 됩니다.
[출처]
CSocket 과
CAsyncSocket에서 Thread문제|작성자
행님
[출처] CSocket 과 CAsyncSocket에서 Thread문제|작성자 행님
CSocket::Attach
Call this member function to attach the hSocket handle to a CSocket object.
BOOL Attach( SOCKET hSocket );
Parameters
- hSocket
- Contains a handle to a socket.
Return Value
Nonzero if the function is successful.
Remarks
The SOCKET handle is stored in the object's m_hSocket data member.
For more information, see Windows Sockets: Using Sockets with Archives. Also see Windows Sockets Programming Considerations in the Platform SDK.
Example
// ... class CSockThread : public CWinThread { // ... Other function and member declarations protected: CSocket m_sConnected; }; SOCKET hConnected; BOOL CSockThread::InitInstance() { // Attach the socket object to the socket handle // in the context of this thread. m_sConnected.Attach(hConnected); return TRUE; } // This listening socket has been constructed // in the primary thread. void CListeningSocket::OnAccept(int nErrorCode) { // This CSocket object is used just temporarily // to accept the incoming connection. CSocket sConnected; Accept(sConnected); // Detach the newly accepted socket and save // the SOCKET handle. hConnected = sConnected.Detach(); // After detaching it, it should no longer be // used in the context of this thread. // Start the other thread. AfxBeginThread(RUNTIME_CLASS(CSockThread)); }
See Also
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_mfc_csocket.3a3a.attach.asp
[출처]
NDK csocket
thread|작성자
spjt