Message-ID: <4BPiHX$w9q@bbs.sdu.edu.cn>
Subject: The Overlapped Model
Date: Sun, 28 Mar 2004 12:04:33 +0000
From: onek.bbs@bbs.sdu.edu.cn (�式�)
Path: news.cnusenet.org!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!i2pn2.pugleaf.net!archive.newsdeef.eu!mbox2nntp-cn.bbs.comp.lang.mbox.zip!archiver1.google.com!news1.google.com!news.glorb.com!border1.nntp.ash.giganews.com!border2.nntp.ash.giganews.com!nntp.giganews.com!feed2.newsreader.com!newsreader.com!maily.cic.tsinghua.edu.cn!netnews.sdu.edu.cn!SDU
Newsgroups: cn.bbs.comp.lang
Organization: 泉������
X-Filename: Programming/M.1080475473.A
Xref: news.cnusenet.org cn.bbs.comp.lang:18074


The overlapped I/O model in Winsock offers applications better system performa
nce than any of the I/O models explained so far. The overlapped model's basic 
design allows your application to post one or more asynchronous I/O requests a
t a time using an overlapped data structure. At a later point, the application
 can service the submitted requests after they have completed. This model is a
vailable on all Windows platforms except Windows CE. The model's overall desig
n is based on the Windows overlapped I/O mechanisms available for performing I
/O operations on devices using the ReadFile and WriteFile functions.

Originally, the Winsock overlapped I/O model was available only to Winsock 1.1
 applications running on Windows NT. Applications could take advantage of the 
model by calling ReadFile and WriteFile on a socket handle and specifying an o
verlapped structure. Since the release of Winsock 2, overlapped I/O has been i
ncorporated into new Winsock functions, such as WSASend and WSARecv. As a resu
lt, the overlapped I/O model is now available on all Windows platforms that fe
ature Winsock 2.

  
 With the release of Winsock 2, overlapped I/O can still be used with the func
tions ReadFile and WriteFile under Windows NT and Windows 2000. However, this 
functionality was not added to Windows 95, Windows 98, and Windows Me. For com
patibility across platforms, you should always consider using the WSARecv and 
WSASend functions instead of the Windows ReadFile and WriteFile functions. Thi
s section will only describe how to use overlapped I/O through the Winsock 2 f
unctions.
 
  

To use the overlapped I/O model on a socket, you must first create a socket th
at has the overlapped flag set. See Chapter 2 for more information on creating
 overlapped enabled sockets. 

After you successfully create a socket and bind it to a local interface, overl
apped I/O operations can commence by calling the Winsock functions listed belo
w and specifying an optional WSAOVERLAPPED structure.

WSASend

WSASendTo

WSARecv

WSARecvFrom

WSAIoctl

WSARecvMsg

AcceptEx

ConnectEx

TransmitFile

TransmitPackets

DisconnectEx

WSANSPIoctl

To use overlapped I/O, each function takes a WSAOVERLAPPED structure as a para
meter. When these functions are called with a WSAOVERLAPPED structure, they co
mplete immediately��regardless of the socket's mode (described at the beginnin
g of this chapter). They rely on the WSAOVERLAPPED structure to manage the com
pletion of an I/O request. There are essentially two methods for managing the 
completion of an overlapped I/O request: your application can wait for event o
bject notification or it can process completed requests through completion rou
tines. The first six functions in the list have another parameter in common: a
 WSAOVERLAPPED_COMPLETION_ROUTINE. This parameter is an optional pointer to a 
completion routine function that gets called when an overlapped request comple
tes. We will explore the event notification method next. Later in this chapter
, you will learn how to use optional completion routines instead of events to 
process completed overlapped requests.

Event Notification
The event notification method of overlapped I/O requires associating Windows e
vent objects with WSAOVERLAPPED structures. When I/O calls such as WSASend and
 WSARecv are made using a WSAOVERLAPPED structure, they return immediately. Ty
pically, you will find that these I/O calls fail with the return value SOCKET_
ERROR and that WSAGetLastError reports a WSA_IO_PENDING error status. This err
or status simply means that the I/O operation is in progress. At a later time,
 your application will need to determine when an overlapped I/O request comple
tes by waiting on the event object associated with the WSAOVERLAPPED structure
. The WSAOVERLAPPED structure provides the communication medium between the in
itiation of an overlapped I/O request and its subsequent completion, and is de
fined as

typedef struct WSAOVERLAPPED
{ 
    DWORD    Internal;
    DWORD    InternalHigh;
    DWORD    Offset;
    DWORD    OffsetHigh;
    WSAEVENT hEvent;
} WSAOVERLAPPED, FAR * LPWSAOVERLAPPED;
The Internal, InternalHigh, Offset, and OffsetHigh fields are all used interna
lly by the system and an application should not manipulate or directly use the
m. The hEvent field, on the other hand, allows an application to associate an 
event object handle with this operation.

When an overlapped I/O request finally completes, your application is responsi
ble for retrieving the overlapped results. In the event notification method, W
insock will change the event-signaling state of an event object that is associ
ated with a WSAOVERLAPPED structure from non-signaled to signaled when an over
lapped request finally completes. Because an event object is assigned to the W
SAOVERLAPPED structure, you can easily determine when an overlapped I/O call c
ompletes by calling the WSAWaitForMultipleEvents function, which we also descr
ibed in the WSAEventSelect I/O model. WSAWaitForMultipleEvents waits a specifi
ed amount of time for one or more event objects to become signaled. We can't s
tress this point enough: remember that WSAWaitForMultipleEvents is capable of 
waiting on only 64 event objects at a time. Once you determine which overlappe
d request has completed, you need to determine the success or failure of the o
verlapped call by calling WSAGetOverlappedResult, which is defined as

BOOL WSAGetOverlappedResult( 
    SOCKET s,
    LPWSAOVERLAPPED lpOverlapped, 
    LPDWORD lpcbTransfer, 
    BOOL fWait, 
    LPDWORD lpdwFlags
);
The s parameter identifies the socket that was specified when the overlapped o
peration was started. The lpOverlapped parameter is a pointer to the WSAOVERLA
PPED structure that was specified when the overlapped operation was started. T
he lpcbTransfer parameter is a pointer to a DWORD variable that receives the n
umber of bytes that were actually transferred by an overlapped send or receive
 operation. The fWait parameter determines whether the function should wait fo
r a pending overlapped operation to complete. If fWait is TRUE, the function d
oes not return until the operation has been completed. If fWait is FALSE and t
he operation is still pending, WSAGetOverlappedResult returns FALSE with the e
rror WSA_IO_INCOMPLETE. Because in our case we waited on a signaled event for 
overlapped completion, this parameter has no effect. The final parameter, lpdw
Flags, is a pointer to a DWORD that will receive resulting flags if the origin
ating overlapped call was made with the WSARecv or the WSARecvFrom function.

If the WSAGetOverlappedResult function succeeds, the return value is TRUE. Thi
s means that your overlapped operation has completed successfully and that the
 value pointed to by lpcbTransfer has been updated. If the return value is FAL
SE, one of the following statements is true:

The overlapped I/O operation is still pending (as we previously described).

The overlapped operation completed, but with errors.

The overlapped operation's completion status could not be determined because o
f errors in one or more of the parameters supplied to WSAGetOverlappedResult.


Upon failure, the value pointed to by lpcbTransfer will not be updated, and yo
ur application should call the WSAGetLastError function to determine the cause
 of the failure.

The following sample of code demonstrates how to structure a simple server app
lication that is capable of managing overlapped I/O on one socket using the ev
ent notification described above.

#define DATA_BUFSIZE					    4096
void main(void)
{
    WSABUF DataBuf;
    char buffer[DATA_BUFSIZE];
    DWORD EventTotal = 0,
          RecvBytes=0,
          Flags=0;
    WSAEVENT EventArray[WSA_MAXIMUM_WAIT_EVENTS];
    WSAOVERLAPPED AcceptOverlapped;
    SOCKET ListenSocket, AcceptSocket;

    // Step 1:
    //  Start Winsock and set up a listening socket
    ...

    // Step 2:
    //  Accept an inbound connection
    AcceptSocket = accept(ListenSocket, NULL, NULL);

    // Step 3:
    //  Set up an overlapped structure

    EventArray[EventTotal] = WSACreateEvent();

    ZeroMemory(&AcceptOverlapped,
        sizeof(WSAOVERLAPPED));
     AcceptOverlapped.hEvent = EventArray[EventTotal];

    DataBuf.len = DATA_BUFSIZE;
    DataBuf.buf = buffer;

    EventTotal++;

    // Step 4:
    //  Post a WSARecv request to begin receiving data
    //  on the socket

    if (WSARecv(AcceptSocket, &DataBuf, 1, &RecvBytes,
        &Flags, &AcceptOverlapped, NULL) == SOCKET_ERROR)
    {
     if (WSAGetLastError() != WSA_IO_PENDING)
     {
         // Error occurred
     }
 }

    // Process overlapped receives on the socket

    while(TRUE)
    {
     DWORD    Index;
        // Step 5:
        //  Wait for the overlapped I/O call to complete
        Index = WSAWaitForMultipleEvents(EventTotal,
            EventArray, FALSE, WSA_INFINITE, FALSE);

        // Index should be 0 because we 
        // have only one event handle in EventArray

        // Step 6:
        //  Reset the signaled event
        WSAResetEvent(
            EventArray[Index - WSA_WAIT_EVENT_0]);

        // Step 7:
        //  Determine the status of the overlapped
        //  request
        WSAGetOverlappedResult(AcceptSocket,
            &AcceptOverlapped, &BytesTransferred,
            FALSE, &Flags);
    
        // First check to see whether the peer has closed
        // the connection, and if so, close the
        // socket

        if (BytesTransferred == 0)
        {
            printf("Closing socket %d\n", AcceptSocket);

            closesocket(AcceptSocket);
            WSACloseEvent(
                EventArray[Index - WSA_WAIT_EVENT_0]);
            return;
        }

        // Do something with the received data 
        // DataBuf contains the received data
        ...

        // Step 8:
        //  Post another WSARecv() request on the socket

        Flags = 0;
        ZeroMemory(&AcceptOverlapped,
            sizeof(WSAOVERLAPPED));

        AcceptOverlapped.hEvent = EventArray[Index - 
            WSA_WAIT_EVENT_0];

        DataBuf.len = DATA_BUFSIZE;
        DataBuf.buf = buffer;

        if (WSARecv(AcceptSocket, &DataBuf, 1,
            &RecvBytes, &Flags, &AcceptOverlapped,
            NULL) == SOCKET_ERROR)
        {
            if (WSAGetLastError() != WSA_IO_PENDING)
            {
                // Unexpected error
            }
        }
    }
}
The application outlines the following programming steps:

Create a socket and begin listening for a connection on a specified port.

Accept an inbound connection.

Create a WSAOVERLAPPED structure for the accepted socket and assign an event o
bject handle to the structure. Also assign the event object handle to an event
 array to be used later by the WSAWaitForMultipleEvents function.

Post an asynchronous WSARecv request on the socket by specifying the WSAOVERLA
PPED structure as a parameter.

Call WSAWaitForMultipleEvents using the event array and wait for the event ass
ociated with the overlapped call to become signaled.

Determine the return status of the overlapped call by using WSA-GetOverlappedR
esult.

Reset the event object by using WSAResetEvent with the event array and process
 the completed overlapped request.

Post another overlapped WSARecv request on the socket.

Repeat steps 5�C8.

This example can easily be expanded to handle more than one socket by moving t
he overlapped I/O processing portion of the code to a separate thread and allo
wing the main application thread to service additional connection requests.
  
 If a Winsock function is called in an overlapped fashion (either by specifyin
g an event within the WSAOVERLAPPED structure or with a completion routine), t
he operation might complete immediately. For example, calling WSARecv when dat
a has already been received and buffered causes WSARecv to return NO_ERROR. If
 any overlapped function fails with WSA_IO_PENDING or immediately succeeds, th
e completion event will always be signaled and the completion routine will be 
scheduled to run (if specified). For overlapped I/O with a completion port, th
is means that completion notification will be posted to the completion port fo
r servicing.
 
  

Completion Routines
Completion routines are the other method your application can use to manage co
mpleted overlapped I/O requests. Completion routines are simply functions that
 you optionally pass to an overlapped I/O request and that the system invokes 
when an overlapped I/O request completes. Their primary role is to service a c
ompleted I/O request using the caller's thread. In addition, applications can 
continue overlapped I/O processing through the completion routine.

To use completion routines for overlapped I/O requests, your application must 
specify a completion routine, along with a WSAOVERLAPPED structure, to an I/O 
bound Winsock function (described previously). A completion routine must have 
the following function prototype:

void CALLBACK CompletionROUTINE(
    DWORD dwError,
    DWORD cbTransferred,
    LPWSAOVERLAPPED lpOverlapped,
    DWORD dwFlags
);
When an overlapped I/O request completes using a completion routine, the param
eters contain the following information:

The parameter dwError specifies the completion status for the overlapped opera
tion as indicated by lpOverlapped.

The cbTransferred parameter specifies the number of bytes that were transferre
d during the overlapped operation.

The lpOverlapped parameter is the same as the WSAOVERLAPPED structure passed i
nto the originating I/O call.

The dwFlags parameter returns any flags that the operation may have completed 
with (such as from WSARecv).

There is a major difference between overlapped requests submitted with a compl
etion routine and overlapped requests submitted with an event object. The WSAO
VERLAPPED structure's event field, hEvent, is not used, which means you cannot
 associate an event object with the overlapped request. Once you make an overl
apped I/O call with a completion routine, your calling thread must eventually 
service the completion routine once it has completed. This requires you to pla
ce your calling thread in an alertable wait state and process the completion r
outine later, after the I/O operation has completed. The WSAWaitForMultipleEve
nts function can be used to put your thread in an alertable wait state. The ca
tch is that you must also have at least one event object available for the WSA
WaitForMultipleEvents function. If your application handles only overlapped re
quests with completion routines, you are not likely to have any event objects 
around for processing. As an alternative, your application can use the Windows SleepEx function to set your thread in an alertable wait state
. Of course, you can also create a dummy event object that is not associated w
ith anything. If your calling thread is always busy and not in an alertable wa
it state, no posted completion routine will ever get called.

As you saw earlier, WSAWaitForMultipleEvents normally waits for event objects 
associated with WSAOVERLAPPED structures. This function is also designed to pl
ace your thread in an alertable wait state and to process completion routines 
for completed overlapped I/O requests if you set the parameter fAlertable to T
RUE. When overlapped I/O requests complete with a completion routine, the retu
rn value is WSA_IO_COMPLETION instead of an event object index in the event ar
ray. The SleepEx function provides the same behavior as WSAWaitForMultipleEven
ts except that it does not need any event objects. The SleepEx function is def
ined as

DWORD SleepEx(
    DWORD dwMilliseconds, 
    BOOL bAlertable
);
The dwMilliseconds parameter defines how long in milliseconds SleepEx will wai
t. If dwMilliseconds is set to INFINITE, SleepEx waits indefinitely. The bAler
table parameter determines how a completion routine will execute. If bAlertabl
e is set to FALSE and an I/O completion callback occurs, the I/O completion fu
nction is not executed and the function does not return until the wait period 
specified in dwMilliseconds has elapsed. If it is set to TRUE, the completion 
routine executes and the SleepEx function returns WAIT_IO_COMPLETION.

The following code outlines how to structure a simple server application that 
is capable of managing one socket request using completion routines as describ
ed earlier.

#define DATA_BUFSIZE    4096

SOCKET AcceptSocket,
       ListenSocket;
WSABUF DataBuf;
WSAEVENT EventArray[MAXIMUM_WAIT_OBJECTS];
DWORD Flags,
      RecvBytes,
      Index;
char buffer[DATA_BUFSIZE];

void main(void)
{
    WSAOVERLAPPED Overlapped;

    // Step 1:
    //  Start Winsock, and set up a listening socket
    ...

    // Step 2:
    //  Accept a new connection
    AcceptSocket = accept(ListenSocket, NULL, NULL);

    // Step 3:
    //  Now that we have an accepted socket, start
    //  processing I/O using overlapped I/O with a
    //  completion routine. To get the overlapped I/O
    //  processing started, first submit an
    //  overlapped WSARecv() request.

    Flags = 0;
        
    ZeroMemory(&Overlapped, sizeof(WSAOVERLAPPED));

    DataBuf.len = DATA_BUFSIZE;
    DataBuf.buf = buffer;
     // Step 4:
    //  Post an asynchronous WSARecv() request
    //  on the socket by specifying the WSAOVERLAPPED
    //  structure as a parameter, and supply  
    //  the WorkerRoutine function below as the 
    //  completion routine

    if (WSARecv(AcceptSocket, &DataBuf, 1, &RecvBytes, 
        &Flags, &Overlapped, WorkerRoutine) 
        == SOCKET_ERROR)
    {
        if (WSAGetLastError() != WSA_IO_PENDING)
        {
            printf("WSARecv() failed with error %d\n", 
                WSAGetLastError());
            return;
        }
    }

    // Because the WSAWaitForMultipleEvents() API
    // requires waiting on one or more event objects,
    // we will have to create a dummy event object.
    // As an alternative, we can use SleepEx()
    // instead.

    EventArray [0] = WSACreateEvent(); 

    while(TRUE)
    {
        // Step 5:
        Index = WSAWaitForMultipleEvents(1, EventArray,
            FALSE, WSA_INFINITE, TRUE);

        // Step 6:
        if (Index == WAIT_IO_COMPLETION)
        {
            // An overlapped request completion routine
            // just completed. Continue servicing 
            // more completion routines.
            continue;
        }
        else
        {
            // A bad error occurred:��stop processing!
            // If we were also processing an event
            // object, this could be an index to
            // the event array.
            return;
        }
    }
}

void CALLBACK WorkerRoutine(DWORD Error, 
                            DWORD BytesTransferred, 
                            LPWSAOVERLAPPED Overlapped,
                            DWORD InFlags)
{
    DWORD SendBytes, RecvBytes;
    DWORD Flags;

    if (Error != 0 ���� BytesTransferred == 0)
    {
        // Either a bad error occurred on the socket
        // or the socket was closed by a peer
        closesocket(AcceptSocket);
        return;
    }

    // At this point, an overlapped WSARecv() request
    // completed successfully. Now we can retrieve the
    // received data that is contained in the variable
    // DataBuf. After processing the received data, we 
    // need to post another overlapped WSARecv() or
    // WSASend() request. For simplicity, we will post 
    // another WSARecv() request.

    Flags = 0;
        
    ZeroMemory(&Overlapped, sizeof(WSAOVERLAPPED));

    DataBuf.len = DATA_BUFSIZE;
    DataBuf.buf = buffer;

    if (WSARecv(AcceptSocket, &DataBuf, 1, &RecvBytes, 
        &Flags, &Overlapped, WorkerRoutine) 
        == SOCKET_ERROR)
    {
        if (WSAGetLastError() != WSA_IO_PENDING )
        {
            printf("WSARecv() failed with error %d\n", 
                WSAGetLastError());
            return;
        }
    }
}
The application illustrates the following programming steps:

Create a socket and begin listening for a connection on a specified port.

Accept an inbound connection.

Create a WSAOVERLAPPED structure for the accepted socket.

Post an asynchronous WSARecv request on the socket by specifying the WSAOVERLA
PPED structure as a parameter and supplying a completion routine.

Call WSAWaitForMultipleEvents with the fAlertable parameter set to TRUE and wa
it for an overlapped request to complete. When an overlapped request completes
, the completion routine automatically executes and WSAWaitForMultipleEvents r
eturns WSA_IO_COMPLETION. Inside the completion routine, then post another ove
rlapped WSARecv request with a completion routine.

Verify that WSAWaitForMultipleEvents returns WSA_IO_COMPLETION.

Repeat steps 5 and 6.

The overlapped model provides high-performance socket I/O. It is different fro
m all the previous models because an application posts buffers to send and rec
eive data that the system uses directly. That is, if an application posts an o
verlapped receive with a 10 KB buffer and data arrives on the socket, it is co
pied directly into this posted buffer. In the previous models, data would arri
ve and be copied to the per-socket receive buffers at which point the applicat
ion is notified of the capability to read. After the application calls a recei
ve function, the data is copied from the per-socket buffer to the application'
s buffer. Chapter 6 will discuss strategies for developing high-performance, s
calable Winsock applications. Chapter 6 will also discuss the WSARecvMsg, Acce
ptEx, ConnectEx, TransmitFile, TransmitPackets, and DisconnectEx API functions
 in more detail.

The disadvantage of using overlapped I/O with events is, again, the limitation
 of being able to wait on a maximum of 64 events at a time. Completion routine
s are a good alternative but care must be taken to ensure that the thread that
 posted the operation goes into an alertable wait state in order for the compl
etion routine to complete. Also, care should be taken to make sure that the co
mpletion routines do not perform excessive computations so that these routines
 may fire as fast as possible under a heavy load.


--

�� ��源:��泉������ http://bbs.sdu.edu.cn [FROM: 202.194.32.132]