Microsoft KB Archive/138694

= FIX: Using CSocket w/ CArchive Causes Block from Extra FD_READ =

Article ID: 138694

Article Last Modified on 11/21/2006

-

APPLIES TO

 Microsoft Foundation Class Library 4.2, when used with:  Microsoft Visual C++ 1.52 Professional Edition

 Microsoft Visual C++ 2.1

 Microsoft Visual C++ 2.2

 Microsoft Visual C++ 4.0 Standard Edition</li></ul>

 Microsoft Visual C++ 4.1 Subscription</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q138694

<div class="symptoms_section">

SYMPTOMS
Using a CArchive object with a CSocket can cause an extra FD_READ notification to be posted when no data is pending. This happens when a block of data is received through the extraction operator ('>>') or CArchive::Read that is larger than the current buffer size of the CArchive object.

This can cause OnReceive to be called when no data is present, which will cause the application to hang indefinitely if a subsequent call to Receive is made.

<div class="cause_section">

CAUSE
The CArchive class automatically buffers data reads and writes. If a call is made to retrieve a block of data larger than the CArchive object's buffer size, then the CArchive class will make two calls to retrieve the data in buffer-size blocks.

When CSocket is used, the end result is two calls to the Receive function. The first call to Receive does not retrieve all of the data currently in the socket's buffer, so the Windows Sockets DLL posts an additional FD_READ notification after this first call. Although the second call to Receive might get the rest of the data from the buffer, the FD_READ notification has already been posted and OnReceive will end up being called later even though there is no data left to read on the socket.

<div class="resolution_section">

RESOLUTION
Make sure there is data in the socket's buffer using CAsyncSocket::IOCtl before attempting to receive. void CMySocket::OnReceive(int nErrorCode) { // TODO: Do some error handling on nErrorCode

DWORD dwBytes; VERIFY(IOCtl(FIONREAD, &dwBytes)); if (0 == dwBytes) // if nothing to read, return return;

do {

// Read your data from your CArchive object

CString strData; m_pMyArchive >> strData;

} while(!m_pMyArchive->IsBufferEmpty); }

<div class="status_section">

STATUS
Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article. This bug was fixed in Visual C++ version 4.2.

<div class="references_section">