怎么理解WSAAsyncSelect()函数??参考:WSAAsyncSelect(ServerSocket, m_hWnd, WM_CLIENT_ACCEPT, FD_ACCEPT
怎么理解WSAAsyncSelect()函数?? 参考: WSAAsyncSelect(ServerSocket, m_hWnd, WM_CLIENT_ACCEPT, FD_ACCEPT); 网上很多内容,有百度百科的,有函数参考手册的,都看的不是很懂。 是不是这个意思: 这个函数将该窗口与网络事件绑定起来,即,只要有网络事件发生,就会触发由WSAAsyncSelect()绑定的自定义消息??[解决办法]
探讨 参考: WSAAsyncSelect(ServerSocket, m_hWnd, WM_CLIENT_ACCEPT, FD_ACCEPT); 网上很多内容,有百度百科的,有函数参考手册的,都看的不是很懂。 是不是这个意思: 这个函数将该窗口与网络事件绑定起来,即,只要有网络事件发生,就会触发由WSAAsyncSelect()绑定的自定义消息??[解决办法] WSAAsyncSelect 利用一个windows窗体消息队列,来接收网络事件
你不需要自定义消息,还有消息映射的方式,重下该窗体的事件处理函数在WM_SOCKET消息分支中使用WSAGETSELECTEVENT(lParam)获取具体的网络事件,代码如下:
#define WM_SOCKET WM_USER + 1
#include <winsock2.h>
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance, LPSTR lpCmdLine,
int nCmdShow)
{
WSADATA wsd;
SOCKET Listen;
SOCKADDR_IN InternetAddr;
HWND Window;
// Create a window and assign the ServerWinProc
// below to it
Window = CreateWindow();
// Start Winsock and create a socket
WSAStartup(MAKEWORD(2,2), &wsd);
Listen = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Bind the socket to port 5150
// and begin listening for connections
InternetAddr.sin_family = AF_INET;
InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
InternetAddr.sin_port = htons(5150);
bind(Listen, (PSOCKADDR) &InternetAddr,
sizeof(InternetAddr));
// Set up window message notification on
// the new socket using the WM_SOCKET define
// above
WSAAsyncSelect(Listen, Window, WM_SOCKET,
FD_ACCEPT │ FD_CLOSE);
listen(Listen, 5);
// Translate and dispatch window messages
// until the application terminates
while (1) {
// ...
}
}
BOOL CALLBACK ServerWinProc(HWND hDlg,UINT wMsg,
WPARAM wParam, LPARAM lParam)
{
SOCKET Accept;
switch(wMsg)
{
case WM_PAINT:
// Process window paint messages
break;
case WM_SOCKET:
// Determine whether an error occurred on the
// socket by using the WSAGETSELECTERROR() macro
if (WSAGETSELECTERROR(lParam))
{
// Display the error and close the socket
closesocket( (SOCKET) wParam);
break;
}
// Determine what event occurred on the
// socket
switch(WSAGETSELECTEVENT(lParam))
{
case FD_ACCEPT:
// Accept an incoming connection
Accept = accept(wParam, NULL, NULL);
// Prepare accepted socket for read,
// write, and close notification
WSAAsyncSelect(Accept, hDlg, WM_SOCKET,
FD_READ │ FD_WRITE │ FD_CLOSE);
break;
case FD_READ:
// Receive data from the socket in
// wParam
break;
case FD_WRITE:
// The socket in wParam is ready
// for sending data
break;
case FD_CLOSE:
// The connection is now closed
closesocket( (SOCKET)wParam);
break;
}
break;
}
return TRUE;
}