FILE: MultiSoc : Illustrates Using Sockets in Multiple ThreadsID: Q175668
|
This sample illustrates how to pass a socket connection between threads in
an MFC application. The sample consists of two projects, the Server and the
Client. The server creates a new thread for each connection to communicate
with the client.
The following file is available for download from the Microsoft
Software Library:
~ MultiSoc.exe
For more information about downloading files from the Microsoft Software
Library, please see the following article in the Microsoft Knowledge Base:
Q119591 How to Obtain Microsoft Support Files from Online Services
void CListensoc::OnAccept(int nErrorCode)
{
// New connection is being established
CSocket soc;
// Accept the connection using a temp CSocket object.
Accept(soc);
// Create a thread to handle the connection.
// The thread is created suspended so that we can
// set variables in CConnectThread before it starts executing.
CConnectThread* pThread =
(CConnectThread*)AfxBeginThread(
RUNTIME_CLASS(CConnectThread),
THREAD_PRIORITY_NORMAL,
0,
CREATE_SUSPENDED);
...
// Pass the socket to the thread by passing the socket handle.
// You cannot pass a CSocket object across threads.
pThread->m_hSocket = soc.Detach();
// Now start the thread.
pThread->ResumeThread();
CAsyncSocket::OnAccept(nErrorCode);
}
InitInstance of the thread.
BOOL CConnectThread::InitInstance()
{
...
// Attach the socket handle to a CSocket object.
// This makes sure that the socket notifications are sent
// to this thread.
m_socket.Attach(m_hSocket);
...
}
The above code makes sure that the socket is set up correctly in the
secondary thread.
© Microsoft Corporation 1997, All Rights Reserved.
Contributions by Sridhar S Madhugiri, Microsoft Corporation
Additional query words: socket thread multithreaded
Keywords : kbfile kbnetwork kbsample kbAPI kbMFC kbSDKPlatform kbThread KbUIDesign kbVC kbVC210 kbVC220 kbVC400 kbVC410 kbVC420 kbVC500 kbVC600 kbWinsock kbGrpNet
Version :
Platform :
Issue type : kbhowto
Last Reviewed: July 9, 1999