求助WSAAsyncselect函数的应用
// WSAAsynSelect.cpp : 定义应用程序的入口点。//
#include "stdafx.h"
#include "WSAAsynSelect.h"
#define MAX_LOADSTRING 100
#define WM_SOCKET WM_USER + 1
typedef struct DATA
{
HWND hDlg;
SOCKET s;
}DATA;
// 全局变量:
HINSTANCE hInst; // 当前实例
TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名
// 此代码模块中包含的函数的前向声明:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), NULL, About); //这里是一个模态对话框
return 0;//(int) msg.wParam;
}
// “关于”框的消息处理程序。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
static SOCKET s;
struct sockaddr_in addr;
static WSADATA wsd;
SOCKET c_s;
int i;
char xie[50];
switch (message)
{
case WM_INITDIALOG:
if(!WSAStartup(MAKEWORD(2,2),&wsd)) //加载winsocket 动态库
{
s = socket(AF_INET,SOCK_STREAM,0); //创建套节字
if(s == SOCKET_ERROR)
{
MessageBox(hDlg,TEXT("创建套接字失败!!!!"),TEXT("提示"),MB_OK);
WSACleanup();
EndDialog(hDlg, LOWORD(wParam));
}
addr.sin_addr.S_un.S_addr = inet_addr("192.168.0.100"); //取得IP地址
addr.sin_family = AF_INET; //TCP/IP模式
addr.sin_port = htons(5150); //设置端口号
if(bind(s,(PSOCKADDR)&addr,sizeof(sockaddr_in)) == SOCKET_ERROR) //邦定套节字
{
MessageBox(hDlg,TEXT("邦定套接字失败!!!!"),TEXT("提示"),MB_OK);
WSACleanup();
EndDialog(hDlg, LOWORD(wParam));
}
//以下是在对话框的静态文本中显的IP和端口
i = wsprintfA(xie,"%s",inet_ntoa(addr.sin_addr));
xie[i] = 0;
SetWindowTextA(GetDlgItem(hDlg,IDC_IP),xie);
i = wsprintfA(xie,"%d",ntohs(addr.sin_port));
xie[i] = 0;
SetWindowTextA(GetDlgItem(hDlg,IDC_PORT),xie);
WSAAsyncSelect(s,hDlg,WM_SOCKET,FD_ACCEPT | FD_CLOSE); 将套节字加入异步事件中并发送消息到hDlg窗口中
listen(s,40); //开始监听
}
else
{
MessageBox(hDlg,TEXT("加载winsocket动态库失败!!!!"),TEXT("提示"),MB_OK);
WSACleanup();
EndDialog(hDlg, LOWORD(wParam));
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
WSAAsyncSelect(wParam,hDlg,0,0);
closesocket(s);
WSACleanup();
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
case WM_SOCKET: //网络事件
if(WSAGETSELECTERROR(lParam))
{
MessageBox(hDlg,TEXT("存在网络错误"),TEXT("提示"),MB_OK);
closesocket(wParam);
return (INT_PTR)TRUE;
}
switch(WSAGETSELECTEVENT(lParam))
{
case FD_ACCEPT: //在这里就有错误了,一旦有客户机连接上,就会无限的接收到该消息而且c_s套节字都是些SOCKET_ERROR
c_s = accept(wParam,(struct sockaddr*)&addr,&i); //请问大侠们能否帮我找出是什么原因么,书上的代码都行不通!!!!
if(c_s == SOCKET_ERROR) return (INT_PTR)TRUE;
i = wsprintfA(xie,"客户机地址:%s",inet_ntoa(addr.sin_addr));
xie[i] = 0;
SendMessageA(GetDlgItem(hDlg,IDC_LIST1),LB_ADDSTRING,0,(LPARAM)xie);
WSAAsyncSelect(c_s,hDlg,WM_SOCKET,FD_READ | FD_WRITE | FD_CLOSE);
closesocket(c_s);
break;
}
return (INT_PTR)TRUE;
}
return (INT_PTR)FALSE;
}