WSAAsyncSelect基于Windows消息机制异步I/O模型,为特定网络事件指定系统通知信息.
Applies to:
The
Syntax
int WSAAsyncSelect( _In_SOCKET s, _In_ HWND hWnd, _In_ unsigned int wMsg, _In_ long lEvent );
Parameters
-
s
-
A descriptor that identifies the socket for which eventnotification is required.
hWnd
-
A handle that identifies the window that will receive a messagewhen a network event occurs.
wMsg
-
A message to be received when a network event occurs.
lEvent
-
A bitmask that specifies a combination of network events in whichthe application is interested.
Return value
If the
Remarks
The
Value | Meaning |
---|---|
FD_READ | Set to receive notification of readiness for reading. |
FD_WRITE | Wants to receive notification of readiness for writing. |
FD_OOB | Wants to receive notification of the arrival of OOB data. |
FD_ACCEPT | Wants to receive notification of incoming connections. |
FD_CONNECT | Wants to receive notification of completed connection or multipointjoin operation. |
FD_CLOSE | Wants to receive notification of socket closure. |
FD_QOS | Wants to receive notification of socket Quality of Service (QoS)changes. |
FD_GROUP_QOS | Wants to receive notification of socket group Quality of Service(QoS) changes (reserved for future use with socket groups).Reserved. |
FD_ROUTING_INTERFACE_CHANGE | Wants to receive notification of routing interface changes for thespecified destination(s). |
FD_ADDRESS_LIST_CHANGE | Wants to receive notification of local address list changes for thesocket protocol family. |
(2)参数3-wMsg:为套接口事件设定1Event通知消息通常形式(WM_USER + n)
如 #defineWM_USER_SERVER
(3)参数2-bWnd指定系统通知消息wMsg的窗口句柄.函数若调用成功,
WSAAsyncSelect返回0;否则返回SOCKET_ERROR,这时可用WSAGetLastError来获取错误码.
事实上,成功发送一次消息,通知机制会暂停工作直到有重新激活消息通知机制到来.才可重新激活事件.
水平触发:FD_READ,FD_OOB和FD_ACCEPT 即重新激活,需要引发消息发送的条件.
边缘触发:FD_QOS,FD_GROUP_QOS等.
同一接口多次调用WSAAsyncSelect函数,只有最后一次生效.
因此:
WSAAsyncSelect(s, m_hWnd, WM_USER_SERVER,FD_READ),加上
WSAAsyncSelect(s, m_hWnd, WM_USER_SERVER,FD_CLOSE) 并不等于
WSAAsyncSelect(s, m_hWnd, WM_USER_SERVER,FD_READ | FD_CLOSE)
取消套接口上的I/O事件消息通知:、
WSAAsyncSelect(s, hWnd, 0, 0)
在MFC编程环境中,使用该消息处理函数
BEGIN_MESSAGE_MAP(CXXXDlg, CDialog)
END_MESSAGE_MAP()
处理消息函数声明为:
afx_msg void OnSERVERMsg(WPARAM wparam,LPARAM lParam);
它定义为:
void CXXXDlg::OnServerMsg(WPARAM wParam,LPARAM lParam)
{
}
switch(WSAGETSELECTEVENT(lParam)){
case FD_READ:
case FD_CLOSE:
default;
}
}
其中函数会接受到两个参数wParam 和 lParam。
其中 wParam参数指明网络事件套接口,多个套接口指定同一个用户消息,那么就需要根据wParam判断到底是哪个套接口待处理。
lParam参数包含两信息:底字指定发生网络事件,高字包含可能出现错误带代码。
另外 OnServerMsg函数中出现两个宏定义
#defineWSAGETSELECTERROR(lParam)
#defineWSAGETSELECTEVENT(lparam)
一般来讲,当用户收到第一个FD_WRITE用户消息时就可以向套接口写数据,直到碰到WSAEWOULBALOCK错误时才
等待下一次FD_WRITE通知消息。
总结:WSAAsynSelect在MFC中使用流程
(1)、使用#define语句定义套接口网络事件设置用户消息值,一般为WM_USER+N形式。
(2)、调用WSAAsynsSelect函数,为套接口设定"网络事件-用户消息-消息接收窗体"的对应关系。
(3)、在消息接收窗体的代码的消息映射模块中,加入ON_MESSAGE宏,设定用户消息的处理函数。
(4)、编写用户处理函数,该函数应该首先使用WSAGETSELECTERROR宏判断是否有错误发生:
然后根据wParam值了解是哪一个套接口上发生了网络事件从而引起用户消息被发送:最后使用
WSAGETSELECTEVENT宏来了解所发生的网络事件,从而进行相应处理。