使用异步选择函数WSAAsyncSelect

来源:互联网 发布:开机windows update 编辑:程序博客网 时间:2024/05/22 03:20
Windows Sockets为了支持Windows消息驱动机制,使应用程序开发者能够方便地处理网络通信,它对网络事件采用了基于消息的异步存取策略。Windows Sockets的异步选择函数WSAAsyncSelect()提供了消息机制的网络事件选择(lEvent),当使用它登记的网络事件发生时,Windows应用程序相应的窗口(hWnd)函数将收到一个消息(wMsg),消息中指示了发生的网络事件,以及与事件相关的一些信息(在附加参数WPARAM和LPARAM中)。
int WSAAsyncSelect(
  SOCKET s,          
  HWND hWnd,         
  unsigned int wMsg, 
  long lEvent        
);

The WSAAsyncSelect function is used to request that Ws2_32.dll should send a message to the window hWnd whenever it detects any of the network events specified by the lEvent parameter. The message that should be sent is specified by the wMsg parameter. The socket for which notification is required is identified by the s parameter.

The WSAAsyncSelect function automatically sets sockets to nonblocking mode, regardless of the value of lEvent. See the ioctlsocket functions for information on how to set the nonblocking socket back to blocking mode.


When one of the nominated network events occurs on the specified socket s, the application's window hWnd receives message wMsg. The wParam parameter identifies the socket on which a network event has occurred. The low word of lParam specifies the network event that has occurred. The high word of lParam contains any error code. The error code be any error as defined in Winsock2.h.

所以,较好的编程风格是在该自定义消息的处理函数中传递WPARAM和LPARAM参数,然后在该消息处理函数内部,用switch语句来判断lParam的低地址来获取是哪种网络事件发生,以便采取相应操作。