Click here to Skip to main content
Click here to Skip to main content

Winsock2 Network Events

, 1 May 2001
Rate this:
Please Sign up or sign in to vote.
Tutorial on the use of Network Events under Winsock2

Introduction

Well, first off let me say this is my first article that I am posting here so please forgive any terrible errors that I make. I scanned over many of the articles in the networking section of the Code Project and couldn't find any that were relevant to using Winsock2 Network Events. Unfortunately this came at a time when I was looking to implement some functionality in my program that used them. That being the case, I bit the bullet and cracked open the books. (Along with faithful MSDN of course.)

My Assumptions

There are some assumptions that I am making about the readers of this article. They are:

  • Familiar with MFC 4.2 and VC. (These are obviously a must)
  • Understand the difference between synchronous and asynchronous
  • A basic understanding of socket programming. Nothing extremely heavy is required but you should already know how to set up a socket and about the different states it can be in, etc...

Why Network Events?

When I first examined the problem I was faced with, I had three different options to use. The first was to use regular socket calls under Winsock 1.1.   The next approach I came across, which I might add only lasted as long as it took me to read it, was to use notification of network "events" through windows messages. This poised a very big problem considering the program I was integrating this code into had no message pump. This brings us to the solution: Notification through WSA Events.

How do they Work?

The idea is that there are a limited number of things that most people do on a certain socket. You send data, receive data, connect to another socket, accept incoming connect requests and you close a socket. There are perhaps a couple more but we will only focus on the major ones for this article.  When one of these things occurs, an event you associated with it will signal and you do what ever is necessary. The network events that can be handled are as follows (again, these are only the ones we are going to be discussing):

  • FD_ACCEPT
  • FD_READ
  • FD_WRITE
  • FD_CLOSE
  • FD_CONNECT

Lets set up a small sample to demonstrate. The first thing you need to do is initialize the winsock2 library. There is probably more than one way to do this but here is how I go about it.

WSADATA wsd;
LPFN_WSASTARTUP lpf = 
    (LPFN_WSA_STARTUP)::GetProcAddress( 
        ::LoadLibrary("WS2_32.DLL"), "WSAStartup");
lpf(0x0202, &wsd);

The initialization can be done anywhere, as far as I know, provided that it is done before you use any calls to winsock functions. The next important thing to do is to create the event we want to use to determine when one of network events takes place. To do this, use the Winsock2 API call to ::WSACreateEvent(); After the event is created it must be associated with the socket that the events will occur on and which events it is to handle. That will be done with WSAEventSelect(...). For the following we are setting up an event to signal on the arrival of a request to connect. This is usually done on a listening socket.  For us, this socket is SOCKET m_listen . It will look like this: 

WSAEVENT hEvent = WSA_INVALID_EVENT;
hEvent = WSACreateEvent();
::WSAEventSelect(m_listen, hEvent, FD_ACCEPT);		

If the socket in question was our data transfer socket, say for example, SOCKET m_socket, that it would more likely look like this:

WSAEVENT hDataEvent = WSA_INVALID_EVENT;
hDataEvent = WSACreateEvent();
::WSAEventSelect(m_socket, hDataEvent, FD_WRITE | FD_READ | FD_CLOSE);

It should be noted that it is not possible to use two different event objects to listen for different network events on the same socket. You cannot do the following:  

WSAEVENT hEvent1 = WSA_INVALID_EVENT;
WSAEVENT hEvent2 = WSA_INVALID_EVENT;

hEvent1 = WSACreateEvent();
hEvent2 = WSACreateEvent();

::WSAEventSelect(m_socket, hEvent1, FD_READ);
::WSAEventSelect(m_socket, hEvent2, FD_WRITE);

Handling the Event Notifications

Now that the events we are going to use are set up, we need a way of waiting on and handling them. The events are actually just regular Win32 events which makes them a HANDLE. The function we can use to wait for these events to occur is WSAWaitForMultipleEvents(...). This function will just cause the thread it is in to sleep until a network event that we are handling occurs. An example of this would be:

//Assume m_listen  and  m_data  are both vaild sockets

WSAEVENT hEvent1 = WSACreateEvent();
WSAEVENT hEvent2 = WSACreateEvent();

::WSAEventSelect(m_listen, hEvent1,  FD_ACCEPT);
::WSAEventSelect(m_data, hEvent2,  FD_READ | FD_CLOSE);

WSAEVENT* pEvents = (WSAEVENT*)::calloc(2, WSAEVENT);
pEvents[0] = hEvent1;
pEvents[1] = hEvent2;

int nReturnCode = ::WSAWaitForMultipleEvents(2, pEvents, 
    FALSE, INFINITE, FALSE);

If waiting for only one event the same function can be used. Just alter it to look something like:

int nReturnCode = ::WSAWaitForMultipleEvents(1, &hEvent1, 
    FALSE, INFINITE, FALSE); 

The first parameter is the number of events that you want to wait on. The second is a pointer to an array of the events you want to wait on. The third event is a BOOL value that determines whether or not the wait function should continue to sleep until all events have signaled. This usually will be false but you may find some need to wait on all events. The fourth parameter is how long you want to wait. Since I usually put this functionality in another thread I leave it at infinite. If you have this in your main thread, you may want to limit it to 5 seconds or some other timeout that relates to your application. The fourth parameter is whether or not you want it to be alertable. Now once an event fires there should be something that handles each event. The first thing that needs to be done is to figure out exactly which event fired. For this we can use the function ::WSAEnumNetworkEvents(...). One of the parameters for this function is a structure called WSANETWORKEVENTS . Moving along with the code we had above, we would proceed to do the following:

WSANETWORKEVENTS hConnectEvent;
WSANETWORKEVENTS hProcessEvent;

::WSAEnumNetworkEvents(m_listen, hConnectEvent, &wsaConnectEvents);
::WSAEnumNetworkEvents(m_data,   hProcessEvent, &wsaProcessEvents);

After that has been completed you have the event that fired on one of the sockets. Now we need to break it down and handle it per event so that the correct action is taken for the correct event. This is done as follows:

if(
    //checks to see if this was the event that occurred
    (wsaConnectEvents.lNetworkEvents & FD_ACCEPT) &&	
    //ensures that there was no error
   (wsaConnectEvents.iErrorCode[FD_ACCEPT_BIT] == 0) )	
{
    /*
        ....
        //Handle Processing here
        ....
    */
 }

This manner of checking can be done for each WSAEVENT you have set up and for each network event that the WSAEVENT will signal for. All that you must do it to change the FD_ACCEPT to whatever network event you are handling and change the error check bit to the appropriate variable.

Conclusion

I hope this helps somebody writing network applications. I have tried to compact a lot of information into a small article so I know that it may not answer all questions. Feel free to email me or post questions below and I will try to answer all that I can. I would also like to apologize for not having some sort of demo app to go along with this article but I am very busy right now and all the source that I currently have that uses network events is owned by my company.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Joseph Dempsey
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
Generalnetwork availability notification Pinmemberm_shezy12-Nov-06 18:43 
GeneralSUPPORT NO LONGER AVAILABLE PinmemberJoseph Dempsey28-Oct-05 11:02 
GeneralLPFN_WSA_STARTUP PinsussJockeP11-Oct-05 2:22 
GeneralSample code PinsussJockeP11-Oct-05 0:55 
Generalerror in header file Pinmembertasleem1436-Jun-05 2:37 
GeneralUsing regular Win32 Events instead of WSAEVENTs Pinmembereasdfeadsfadsfwerfaesff15-Jul-04 13:56 
QuestionHow to monitor in and out bandwidth of a single APP Pinmembertyounsi4-May-04 23:50 
QuestionQuestion ? Pinmemberdddv14-Feb-04 17:41 
AnswerRe: Question ? PinmemberJoseph Dempsey14-Feb-04 18:26 
GeneralNetwork Event Pinmemberjohnsb223-Jan-04 15:14 
GeneralRe: Network Event PinmemberSpencer Bray2-Nov-04 11:15 
GeneralProblem getting FD_READ Event: PinmemberJeanChretien14-Jul-03 5:13 
GeneralRe: Problem getting FD_READ Event: PinmemberJoseph Dempsey14-Jul-03 5:24 
GeneralRe: Problem getting FD_READ Event: PinmemberJeanChretien14-Jul-03 5:55 
GeneralRe: Problem getting FD_READ Event: PinmemberJoseph Dempsey14-Jul-03 8:08 
GeneralWSAEnumNetworkEvents returns but no network event is detected Pinmemberjpverar11-Feb-03 11:36 
GeneralRe: WSAEnumNetworkEvents returns but no network event is detected PinmemberJoseph Dempsey12-Feb-03 0:47 
GeneralRe: WSAEnumNetworkEvents returns but no network event is detected Pinmemberjpverar12-Feb-03 1:19 
GeneralWSAEnumNetworkEvents returns but no network event is detected Pinmemberjpverar11-Feb-03 11:36 
GeneralHere's a pretty good example PinsussDavid Jonas28-Sep-02 21:06 
GeneralRe: Here's a pretty good example PinsussAnonymous22-Jan-03 10:14 
Questionsample, multiple events, references? Pinmemberjnettleton15-Aug-02 8:48 
GeneralWSA Pinmembershotgun20-Jul-02 4:29 
GeneralRe: WSA PinmemberJoseph Dempsey21-Jul-02 18:01 
GeneralWSAEnumNetworkEvents PinmemberAnonymous21-Jun-02 1:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 2 May 2001
Article Copyright 2001 by Joseph Dempsey
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid