How to accept sockets and read data from themn asynchronously with winsock 2?

  c++, winapi, windows, winsock2

I remember from when I was writing code to watch directory changes in WinAPI, I would get an event for each "listener", add an additional one for canceling the watching and did something like this:

// used to cancel the waiting (eg. program shutting down)
HANDLE* cancelEvent = ... create it somehow ...;
// Waiting for dir changes in dir 1
HANDLE* dirOneWatch = ...;
// Waiting for dir changes in dir 2
HANDLE* dirTwoWatch = ...;

//  array of handles
HANDLE* handles[] = {cancelEvent, dirOneWatch, dirTwoWatch};
DWORD result = WaitForMultipleObjects(3, events, false, INFINITE);

And if either dir changed, or cancellation event was triggered, this function would stop blocking and tell me which one of the things has happened.

So my question is how to do this with winsock. Right now, I have a program based on this example: Complete Winsock Server Code

So this is how I wait for connection, this blocks:

SOCKET ClientSocket = accept(_private->ListenSocket, NULL, NULL);

And reading from the socket is also blocking:

   constexpr size_t len = 64;
   const char buffer[len];
   recv(ClientSocket, buffer, len, 0);

To be able to do more things at once, I’d need one thread per client PLUS one for accepting them. I don’t like that AT all. Instead, I’d like something like:

   WINSOCKEVENT* recvEvent = recv(ClientSocket, buffer, len, 0);
   WINSOCKEVENT* acceptNewEvent = accept(_private->ListenSocket, NULL, NULL);
   DWORD result = WinsockWaitForMultipleEvents(... like in the example above...);

Is there a way to do that? Or is there another native windows lib to do socket communication without a bunch of threads?

Please note that I am writing the code as a learning exercise on making a simple server, thus I don’t want to use any external dependencies except what is available on a given OS, which is windows at the moment.

Source: Windows Questions

LEAVE A COMMENT