Using CAsynSocket, how to catch socket operations' exit code?

181 Views Asked by At

Please, someone kindly help me how to catch socket operation's error from CAsyncSocket Class.

If I do this:

int iLen = recv(socket, socketBuffer, sizeBuffer, 0);
if(iLen==SOCKET_ERROR) {
   //handle error here
} else {
   //do something with the received data
}

It always returns error, which is WSAEWOULDBLOCK, and the same for other operation like send(), connect(), etc...
According to MSDN, it's not a fatal error, and some time must elapse for the actions to be finished.

So how can I actually check every time my program did recv() or send() correctly?

1

There are 1 best solutions below

10
Andrew Komiagin On

First of all you should not mix CAsyncSocket API and Berkley Socket API.

Your OnReceive handler should look like this:

    CByteArray InBuffer; 
    InBuffer.SetSize(DEFAULT_RX_BUFFER_SIZE);       
    int nBytes = Receive(InBuffer.GetData(), (int)InBuffer.GetSize());

    switch (nBytes)
    {
        case 0:
            ShutDown(CAsyncSocket::both);
            break;
        case SOCKET_ERROR:
            if (::GetLastError() != WSAEWOULDBLOCK) 
                ShutDown(CAsyncSocket::both);
            else
                AsyncSelect();
            break;
        default:
            {
                // TODO: data processing goes here
            }
            break;  
    }