Winsock provides another useful asynchronous event notification I/O model that
is similar to the WSAAsyncSelect model that allows an application to receive
event-based notification of network events on one or more sockets. This model
is similar to the WSAAsyncSelect model because your application receives and p
rocesses the same network events listed in Table 5-3 that the WSAAsyncSelect m
odel uses. The major difference with this model is that network events are not
ified via an event object handle instead of a window procedure.
Event Notification
The event notification model requires your application to create an event obje
ct for each socket used by calling the WSACreateEvent function, which is defin
ed as
WSAEVENT WSACreateEvent(void);
The WSACreateEvent function simply returns a manual reset event object handle.
Once you have an event object handle, you have to associate it with a socket
and register the network event types of interest, as shown in Table 5-3. This
is accomplished by calling the WSAEventSelect function, which is defined as
int WSAEventSelect(
SOCKET s,
WSAEVENT hEventObject,
long lNetworkEvents
);
The s parameter represents the socket of interest. The hEventObject parameter
represents the event object��obtained with WSACreateEvent��to associate with t
he socket. The last parameter, lNetworkEvents, represents a bitmask that speci
fies a combination of network event types (listed in Table 5-3) that the appli
cation is interested in. For a detailed discussion of these event types, see t
he WSAAsyncSelect I/O model discussed previously.
The event created for WSAEventSelect has two operating states and two operatin
g modes. The operating states are known as signaled and non-signaled. The oper
ating modes are known as manual reset and auto reset. WSACreateEvent initially
creates event handles in a non-signaled operating state with a manual reset o
perating mode. As network events trigger an event object associated with a soc
ket, the operating state changes from non-signaled to signaled. Because the ev
ent object is created in a manual reset mode, your application is responsible
for changing the operating state from signaled to non-signaled after processin
g an I/O request. This can be accomplished by calling the WSAResetEvent functi
on, which is defined as
BOOL WSAResetEvent(WSAEVENT hEvent);
The function takes an event handle as its only parameter and returns TRUE or F
ALSE based on the success or failure of the call. When an application is finis
hed with an event object, it should call the WSACloseEvent function to free th
e system resources used by an event handle. The WSACloseEvent function is defi
ned as
BOOL WSACloseEvent(WSAEVENT hEvent);
This function also takes an event handle as its only parameter and returns TRU
E if successful or FALSE if the call fails.
Once a socket is associated with an event object handle, the application can b
egin processing I/O by waiting for network events to trigger the operating sta
te of the event object handle. The WSAWaitForMultipleEvents function is design
ed to wait on one or more event object handles and returns either when one or
all of the specified handles are in the signaled state or when a specified tim
eout interval expires. WSAWaitForMultipleEvents is defined as
DWORD WSAWaitForMultipleEvents(
DWORD cEvents,
const WSAEVENT FAR * lphEvents,
BOOL fWaitAll,
DWORD dwTimeout,
BOOL fAlertable
);
The cEvents and lphEvents parameters define an array of WSAEVENT objects in wh
ich cEvents is the number of event objects in the array and lphEvents is a poi
nter to the array. WSAWaitForMultipleEvents can support only a maximum of WSA_
MAXIMUM_WAIT_EVENTS objects, which is defined as 64. Therefore, this I/O model
is capable of supporting only a maximum of 64 sockets at a time for each thre
ad that makes the WSAWaitForMultipleEvents call. If you need to have this mode
l manage more than 64 sockets, you should create additional worker threads to
wait on more event objects. The fWaitAll parameter specifies how WSAWaitForMul
tipleEvents waits for objects in the event array. If TRUE, the function return
s when all event objects in the lphEvents array are signaled. If FALSE, the fu
nction returns when any one of the event objects is signaled. In the latter ca
se, the return value indicates which event object caused the function to retur
n. Typically, applications set this parameter to FALSE and service one socket event at a time. The dwTimeout parameter specifies how long (in
milliseconds) WSAWaitForMultipleEvents will wait for a network event to occur
. The function returns if the interval expires, even if conditions specified b
y the fWaitAll parameter are not satisfied. If the timeout value is 0, the fun
ction tests the state of the specified event objects and returns immediately,
which effectively allows an application to poll on the event objects. If no ev
ents are ready for processing, WSAWaitForMultipleEvents returns WSA_WAIT_TIMEO
UT. If dwsTimeout is set to WSA_INFINITE, the function returns only when a net
work event signals an event object. The final parameter, fAlertable, can be ig
nored when you're using the WSAEventSelect model and should be set to FALSE. I
t is intended for use in processing completion routines in the overlapped I/O
model, which will be described later in this chapter.
Note that by servicing signaled events one at a time (by setting the fWaitAll
parameter to FALSE), it is possible to starve sockets toward the end of the ev
ent array. Consider the following code:
WSAEVENT HandleArray[WSA_MAXIMUM_WAIT_EVENTS];
int WaitCount=0, ret, index;
// Assign event handles into HandleArray
while (1) {
ret = WSAWaitForMultipleEvents(
WaitCount,
HandleArray,
FALSE,
WSA_INFINITE,
TRUE);
if ((ret != WSA_WAIT_FAILED) && (ret != WSA_WAIT_TIMEOUT)) {
index = ret - WSA_WAIT_OBJECT_0;
// Service event signaled on HandleArray[index]
WSAResetEvent(HandleArray[index]);
}
}
If the socket connection associated in index 0 of the event array is continual
ly receiving data such that after the event is reset additional data arrives c
ausing the event to be signaled again, the rest of the events in the array are
starved. This is clearly undesirable. Once an event within the loop is signal
ed and handled, all events in the array should be checked to see if they are s
ignaled as well. This can be accomplished by using WSAWaitForMultipleEvents wi
th each individual event handle after the first signaled event and specifying
a dwTimeOut of zero.
When WSAWaitForMultipleEvents receives network event notification of an event
object, it returns a value indicating the event object that caused the functio
n to return. As a result, your application can determine which network event t
ype is available on a particular socket by referencing the signaled event in t
he event array and matching it with the socket associated with the event. When
you reference the events in the event array, you should reference them using
the return value of WSAWaitForMultipleEvents minus the predefined value WSA_WA
IT_EVENT_0. For example:
Index = WSAWaitForMultipleEvents(...);
MyEvent = EventArray[Index - WSA_WAIT_EVENT_0];
Once you have the socket that caused the network event, you can determine whic
h network events are available by calling the WSAEnumNetworkEvents function, w
hich is defined as
int WSAEnumNetworkEvents(
SOCKET s,
WSAEVENT hEventObject,
LPWSANETWORKEVENTS lpNetworkEvents
);
The s parameter represents the socket that caused the network event, and the h
EventObject parameter is an optional parameter representing an event handle id
entifying an associated event object to be reset. Because our event object is
in a signaled state, we can pass it in and it will be set to a non-signaled st
ate. The hEventObject parameter is optional in case you wish to reset the even
t manually via the WSAResetEvent function. The final parameter, lpNetworkEvent
s, takes a pointer to a WSANETWORKEVENTS structure, which is used to retrieve
network event types that occurred on the socket and any associated error codes
. The WSANETWORKEVENTS structure is defined as
typedef struct _WSANETWORKEVENTS
{
long lNetworkEvents;
int iErrorCode[FD_MAX_EVENTS];
} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS;
The lNetworkEvents parameter is a value that indicates all the network event t
ypes (see Table 5-3) that have occurred on the socket.
More than one network event type can occur whenever an event is signaled. For
example, a busy server application might receive FD_READ and FD_WRITE notific
ation at the same time.
The iErrorCode parameter is an array of error codes associated with the events
in lNetworkEvents. For each network event type, there is a special event inde
x similar to the event type names��except for an additional ��_BIT�� string ap
pended to the event name. For example, for the FD_READ event type, the index i
dentifier for the iErrorCode array is named FD_READ_BIT. The following code fr
agment demonstrates this for an FD_READ event:
// Process FD_READ notification
if (NetworkEvents.lNetworkEvents & FD_READ)
{
if (NetworkEvents.iErrorCode[FD_READ_BIT] != 0)
{
printf("FD_READ failed with error %d\n",
NetworkEvents.iErrorCode[FD_READ_BIT]);
}
}
After you process the events in the WSANETWORKEVENTS structure, your applicati
on should continue waiting for more network events on all of the available soc
kets. The following example demonstrates how to develop a server and manage ev
ent objects when using the WSAEventSelect I/O model. The code highlights the s
teps needed to develop a basic server application capable of managing one or m
ore sockets at a time.
SOCKET SocketArray [WSA_MAXIMUM_WAIT_EVENTS];
WSAEVENT EventArray [WSA_MAXIMUM_WAIT_EVENTS],
NewEvent;
SOCKADDR_IN InternetAddr;
SOCKET Accept, Listen;
DWORD EventTotal = 0;
DWORD Index, i;
// Set up a TCP socket for listening on port 5150
Listen = socket (PF_INET, SOCK_STREAM, 0);
InternetAddr.sin_family = AF_INET;
InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
InternetAddr.sin_port = htons(5150);
bind(Listen, (PSOCKADDR) &InternetAddr,
sizeof(InternetAddr));
NewEvent = WSACreateEvent();
WSAEventSelect(Listen, NewEvent,
FD_ACCEPT �� FD_CLOSE);
listen(Listen, 5);
SocketArray[EventTotal] = Listen;
EventArray[EventTotal] = NewEvent;
EventTotal++;
while(TRUE)
{
// Wait for network events on all sockets
Index = WSAWaitForMultipleEvents(EventTotal,
EventArray, FALSE, WSA_INFINITE, FALSE);
Index = Index - WSA_WAIT_EVENT_0;
// Iterate through all events to see if more than one is signaled
for(i=Index; i < EventTotal ;i++
{
Index = WSAWaitForMultipleEvents(1, &EventArray[i], TRUE, 1000,
FALSE);
if ((Index == WSA_WAIT_FAILED) ���� (Index == WSA_WAIT_TIMEOUT))
continue;
else
{
Index = i;
WSAEnumNetworkEvents(
SocketArray[Index],
EventArray[Index],
&NetworkEvents);
// Check for FD_ACCEPT messages
if (NetworkEvents.lNetworkEvents & FD_ACCEPT)
{
if (NetworkEvents.iErrorCode[FD_ACCEPT_BIT] != 0)
{
printf("FD_ACCEPT failed with error %d\n",
NetworkEvents.iErrorCode[FD_ACCEPT_BIT]);
break;
}
// Accept a new connection, and add it to the
// socket and event lists
Accept = accept(
SocketArray[Index],
NULL, NULL);
// We cannot process more than
// WSA_MAXIMUM_WAIT_EVENTS sockets, so close
// the accepted socket
if (EventTotal > WSA_MAXIMUM_WAIT_EVENTS)
{
printf("Too many connections");
closesocket(Accept);
break;
}
NewEvent = WSACreateEvent();
WSAEventSelect(Accept, NewEvent,
FD_READ �� FD_WRITE �� FD_CLOSE);
EventArray[EventTotal] = NewEvent;
SocketArray[EventTotal] = Accept;
EventTotal++;
printf("Socket %d connected\n", Accept);
}
// Process FD_READ notification
if (NetworkEvents.lNetworkEvents & FD_READ)
{
if (NetworkEvents.iErrorCode[FD_READ_BIT] != 0)
{
printf("FD_READ failed with error %d\n",
NetworkEvents.iErrorCode[FD_READ_BIT]);
break;
}
// Read data from the socket
recv(SocketArray[Index - WSA_WAIT_EVENT_0],
buffer, sizeof(buffer), 0);
}
// Process FD_WRITE notification
if (NetworkEvents.lNetworkEvents & FD_WRITE)
{
if (NetworkEvents.iErrorCode[FD_WRITE_BIT] != 0)
{
printf("FD_WRITE failed with error %d\n",
NetworkEvents.iErrorCode[FD_WRITE_BIT]);
break;
}
send(SocketArray[Index - WSA_WAIT_EVENT_0],
buffer, sizeof(buffer), 0);
}
if (NetworkEvents.lNetworkEvents & FD_CLOSE)
{
if (NetworkEvents.iErrorCode[FD_CLOSE_BIT] != 0)
{
printf("FD_CLOSE failed with error %d\n",
NetworkEvents.iErrorCode[FD_CLOSE_BIT]);
break;
}
closesocket(SocketArray[Index]);
// Remove socket and associated event from
// the Socket and Event arrays and decrement
// EventTotal
CompressArrays(EventArray, SocketArray, &EventTotal);
}
}
}
}
The WSAEventSelect model offers several advantages. It is conceptually simple
and it does not require a windowed environment. The only drawback is its limit
ation of waiting on only 64 events at a time, which necessitates managing a th
read pool when dealing with many sockets. Also, because many threads are requi
red to handle a large number of socket connections, this model does not scale
as well as the overlapped models discussed next.
--
[0;1;36m�� ��源:��泉������ http://bbs.sdu.edu.cn [FROM: 202.194.32.132][m