Question : CSocket object in thread

Hi guys/girls,
I've got a really BIG problem and I can't get it fixed.
I need to build a program that can send and receive time after time, without blocking the main program.
I am using a CSocket and I need a thread.
I have to create a socket in the thread and then do something like:

CMySocket mysock;   //CMySocket is my own CSocket Class

LPHOSTENT lpHostInfo;
CString str;
struct in_addr *pinAddr;

lpHostInfo = gethostbyname(ClientName);
pinAddr = ((LPIN_ADDR)lpHostInfo->h_addr_list[0]);
str = inet_ntoa(*pinAddr);

mysock.Create(0, SOCK_STREAM, str);
mysock.Connect(IP, Port);

char buf[500], recv[500];
sprintf(buf,"Configure?");
sprintf(recv,"");

for (int i=0;i<100;i++)
{
     mysock.Send(buf, sizeof(buf), 0);
     mysock.Receive(recv, sizeof(recv),0);
     OutputDebugString(recv);
}

mysock.Close();

}


I always get this error:
First-chance exception in MMClient.exe: 0xC0000005: Access Violation.

And I get a break at some kind of m_pHashTable???

Please help me, because I've been trying to solve this problem for over a month.

Greetz joEp mEloEn

Answer : CSocket object in thread

Hi,

I had the same problem few months ago.
Windows maintains thread specific data for each
socket. when a thread is killed etc. the socket is
invalid. MFC makes thread specific initialization
for each thread.

For the main thread it is automatic. For others try using
WSAStartup() before using sockets and WSACleanup() before
exit from thread.


If you dont want that stuff, or it still gives problems there is one simple solution to it. Always create sockets in the main application thread and pass them on to the thread like this :

CSocket MySocket ;
// Create it and stuff

// Check here for NULL or invalid sockets
SOCKET s = MySocket.Detach() ;

// Pass s into the LPVOID parameter that you pass into
// a thread
CreateThread(,.... , (LPVOID)s ,.....)

-------------------------------------------------------

DWORD MyThread(LPVOID lParam)
{
  // Get the socket parameter you passed
  SOCKET s = (SOCKET)lParam ;

  // Attach it to a new class now !
  CSocket ThreadSock ;
  if( ThreadSock.Attach(s) )
  {
      // Do any thing with the socket here
      // like a normal socket including close
  }
  else
  {
     // Destroy the socket cause it cannot be used
     // since it could not be attached
     closesocket(s) ;
  }
 
  return 0 ;
}




Random Solutions  
 
programming4us programming4us