Derived CAsyncSocket sends duplicate data?
I'm at a loss here. I've looked at it, and it's probably something
simple, but can someone explain why my derived class sends duplicate
sets of data occasionally (IE 1 call to Send makes it received twice on
the other end)?
As far as I can tell, it only occurs when the system is under high CPU
load.
Thanks in advance.
Josh McFarlane
--------
From Header File:
enum SendStatus //State of the Send Buffer
{
SEND_EMPTY, //Empty Send Queue
SEND_ACTIVE //Sending currently in progress
};
CCriticalSection ctSender;
SendStatus c_SendStatus;
size_t bytesSent;
size_t sendlength;
std::vector<BYTE> outBuffer;
-----------
From CPP:
int CInternalSocket::Send(const void* lpBuf, int nBufLen, int)
{
//Need to add DWORD to buffer before sending
DWORD TotalLength = nBufLen + sizeof(DWORD);
DWORD Length = htonl(nBufLen);
{
CSingleLock lock(&ctSender);
lock.Lock();
switch (c_SendStatus)
{
case SEND_EMPTY:
{
bytesSent = 0;
sendlength = TotalLength;
outBuffer.resize(TotalLength, 0);
BYTE* p = &outBuffer[0];
memcpy(p, &Length, sizeof(DWORD));
p += sizeof(DWORD);
memcpy(p, lpBuf, nBufLen);
c_SendStatus = SEND_ACTIVE;
break;
}
case SEND_ACTIVE:
{
size_t oldSize = outBuffer.size();
sendlength = oldSize + TotalLength;
outBuffer.resize(sendlength, 0);
BYTE* p = &outBuffer[oldSize];
memcpy(p, &Length, sizeof(DWORD));
p += sizeof(DWORD);
memcpy(p, lpBuf, nBufLen);
break;
}
}
}
OnSend(ERROR_SUCCESS);
return nBufLen;
}
void CInternalSocket::OnSend(int nErrorCode)
{
CSingleLock lock(&ctSender);
lock.Lock();
if (nErrorCode != ERROR_SUCCESS)
{
//Handle initial socket errors here.
if(pInterface)
{
pInterface->PostThreadMessage(UWM_SOCKET_SENDERROR, nErrorCode,
NULL);
}
return;
}
//Check buffer to make sure that it has data to be sent.
size_t bytesToSend = sendlength - bytesSent;
BYTE* p = &outBuffer[bytesSent];
while(bytesToSend > 0)
{ //Bytes to send
int len = CAsyncSocket::Send(p, bytesToSend);
if (len == SOCKET_ERROR)
{ //Send Error
int lastErr = ::GetLastError();
if (WSAEWOULDBLOCK == lastErr || WSAENOTCONN == lastErr)
{
break;
}
else
{
if(pInterface)
{
pInterface->PostThreadMessage(UWM_SOCKET_SENDERROR, lastErr,
NULL);
}
break;
}
} //Send Error
bytesToSend -= len;
bytesSent += len;
p += len;
} //Bytes to Send
if (bytesSent >= outBuffer.size())
{
bytesSent = 0;
c_SendStatus = SEND_EMPTY;
}
}