// JP opened flex table

Click to See Complete Forum and Search --> : Problem using AfxSocketInit


koryo22
December 23rd, 2007, 08:32 AM
Hi, I have a problem.

I'm trying to make a server applicattion with two threads.
1.- For writting messages to a client.
2.- For listening to messages sent by the client.

The CSocket is a member variable from my dialog initilized (the connection is established ... ) before the threads are created. When I use the socket in the thread for reading I have a problem with:

ASSERT(m_hSocket == INVALID_SOCKET || CAsyncSocket::FromHandle(m_hSocket) != NULL)

I have used the AfxSocketInit in the main thread and in the other two new threads but the problem still persists.

------ MAIN THREAD ----------------

HRESULT hr = ::CoInitialize(NULL);
AfxSocketInit(NULL);
CString szMssg;

m_sockConnection = new CBidirecSocket();
CBidirecSocket sockSrvr;

sockSrvr.Conectar(8686); // Creates our server socket
sockSrvr.Listen(); // Start listening for the client at PORT
sockSrvr.Accept(*(m_sockConnection)); // Use another CSocket to accept the connection

m_sockConnection->Init();
AfxBeginThread(ThreadWriteMessage, this);

----------- THREAD WRITE MESSAGE --------------

HRESULT hr = ::CoInitialize(NULL);
AfxSocketInit(NULL);
CMain* pServer = (CMain*) pVoid;
pServer->m_sockConnection->GetMssg(szMsg2); //<--- This function only calls to the read message of the CSocket. Here is where the problem occurs.


I hope someone can help me. Thanks very much!!!

MikeAThon
December 23rd, 2007, 01:43 PM
CAsyncSocket (and its derived class of CSocket) are explicitly designed to work in singly-threaded applications. It's possible to get these classes to work in a multi-threaded application, but each thread will then be required to run a message pump too. In MFC, a thread with a message pump is called a "UI thread", as opposed to a "worker thread".

If you want to use CAsyncSocket or CSocket across threads, you need to deal also with the hand-off of the underlying socket handle from one thread to another, using Detach() and Attach(). The MFC socket classes are not usable across threads, much like the MFC CWnd calsses.

See these articles for more information:
CAsyncSocket handling in UI threads at http://www.flounder.com/mvp_tips.htm#CAsyncSocket
Asynchronous Socket Programming: KB192570 Done Right at http://www.flounder.com/mvp_tips.htm#Asynchronous

Mike

koryo22
December 25th, 2007, 03:11 AM
Hi!! thanks very much for the help!!

But inside the method wich implements the thread code (method called with AfxBeginThread) the socket that I have to use is... I don't know if I have to use the member atrbute, the member atribute of the thread...

I have tryed to use the first option, use the member atribute directly. But I have aproblem.

Thanks!!!

//JP added flex table