Monday, December 06, 2010

Asynchronous (nonblocking) client socket wrapper class without MFC

Introduction
I created this class while trying to avoid having recv hang/block indefinitely in a simple client application I was working on, without using MFC. recv can hang for a variety of reasons most common is untimely calling of recv or calling it when the remote server didn't send data it was supposed to send, e.g.: because of a malformed request.

Using the code

   #include "XSocket.h"

 
   ....
 
CXSocket mySock;
if (!mySock.Init()) //initalize winsocks
   return false;
 
//////////////////////////////////////////////////////////////////////////
if (!mySock.Connect(pHostName, nPort))
{
   int nError = mySock.GetLastError();
   return false;
}
/////////////////////////////////////////////////////////////////////////
// Send a buffer, 5 seconds timeout
// further error checking omitted for previty
int nLen = 0;
if (mySock.Send(szBuff, strlen(szBuff), nLen, 5000) != E_XSOCKET_SUCCESS)
   return false;
 
/////////////////////////////////////////////////////////////////////////
// Receive server's response, 5 seconds time out
// last argument is optional, if not used Rec will return immediately
do
{
   if (mySock.Recv(szBuff, sizeof(szBuff) - 1, nLen, 5000)
!= E_XSOCKET_SUCCESS)
   {
break;
   }
}
       while (nLen == sizeof(szBuff));
 
 
   //////////////////////////////////////////////////////////////////////////
 
   // Optional: explicitly close the socket, if not called socket will be closed
   // auto on destruction
 
   mySock.Close();

Canceling a request, regardless of timeout:

mySock.Abort();

Read more: Codeproject