Setting Up the Asynchronous SocketsIt’s not as hard as you may think. All it takes is for you to create the socket and then make the call to WSAAsyncSelect(), whose definition is shown below. int PASCAL FAR WSAAsyncSelect(SOCKET s, HWND hwnd, unsigned int wMsg, long lEvent); And here we have the parameter explanations.
Now then! We know how to do it, so let’s do it already. Below is a short code segment involving creating a socket and making it asynchronous, first for a client, then for a server. // the message we'll use for our async notification #define WM_WSAASYNC (WM_USER +5) // create and test the socket Port = socket(AF_INET, SOCK_STREAM, 0); if (Port == INVALID_SOCKET) return(FALSE); // make the socket asynchronous and notify of read, write, connect and close events // this is the client socket WSAAsyncSelect(Port, hwnd, WM_WSAASYNC, FD_WRITE | FD_CONNECT | FD_READ | FD_CLOSE); // make the socket asynchronous and notify of read, write, accept and close events // this is the server socket WSAAsyncSelect(Port, hwnd, WM_WSAASYNC, FD_READ | FD_WRITE | FD_ACCEPT | FD_CLOSE); Of course, we wouldn’t put the client and server sockets in the same app, I’m just trying to save space here. Now, take note because this is important: You cannot perform any actions on the socket until you have declared it asynchronous. Why? Let’s say you create the socket and then send() something off quick quick. Well congratulations, you just made it a blocking socket, and now your program is hung up waiting for the send() to complete. Oh yes, you can still change it to asynchronous with WSAAsyncSelect() it’s just that it’s going to cause some problems stopping execution like that. Also notice I had to create a custom message called WM_WSAASYNC. I did this using one of Windows’ custom messages. Nothing big or worth explaining - just follow my lead. By the way, you can call this message whatever the hell you want, it doesn’t have to be WM_WSAASYNC. (Although keeping the WM_ part would be nice for people reading your code) |