Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I pass socket into thread?

Status
Not open for further replies.

Aunthas

Programmer
Oct 8, 2002
7
0
0
TH
Help me plz!!!!!
I passed the socket to my thread but it can't receive any message!!!!!!!!!!!
Did I do something wrong?

I have a main class CServerDlg which accepts the socket connection in this method.

void CServerDlg::processPendingAccept()
{
CClientConnSocket* socClientConn = new CClientConnSocket();

if (m_socListening->Accept(*socClientConn))
{
SOCKET hSocClientConn = socClientConn->Detach();
CServerChild* threadServerChild = new CServerChild(this, hSocClientConn);

threadServerChild->CreateThread()
}
}

Class CServerChild ,extends from CWinThread, has the constructor and InitInstance() like this :-

CServerChild::CServerChild(CServerDlg* pDoc, SOCKET hSocClientConn)
{
m_hSoc = hSocClientConn;
m_pDoc = pDoc;
}

BOOL CServerChild::InitInstance()
{
m_socClientConn = new CClientConnSocket();
m_socClientConn->Attach(m_hSoc);
m_socClientConn->Init(this);
m_pFile = new CSocketFile(m_socClientConn);
m_pArchiveIn = new CArchive(m_pFile,CArchive::load);
m_pArchiveOut = new CArchive(m_pFile,CArchive::store);

return CWinThread::InitInstance();
}
 
I think, You have at least synchronisation problem.
CreateThread() starts creating thread, but initializing a socket need some time, may be next functions will be called before Your socket really was initialized. Try to use mutex or semaphore to avoid it.
There is MTGDI sample to see how right work with threads.
If it is Your first program with threads or sockets, make it working without threads first.
There is a good sample with MFC- sockets httpsvr.
 
Hello Aunthas, there is also another very good CSocket example (client/server model) at:


With step-by-step building proceedures. Now, I may be wrong but I believe that there is some kind of problem using the same socket across two threads. I could never get it to work that way either! Now I just stick my socket handlers in the same thread (so that the socket is created in the thread that it is using to send/receive).
tellis.gif

[sup]programmer (prog'ram'er), n A hot-headed, anorak wearing, pimple-faced computer geek.[/sup]​
 
hi
u can pass the pointer to structure in the thread on AfxBeginThread().

do add the CSocket class in structure as a member.(declare it in the structure) It may help u
bye
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top