#include <WINSOCK2.H>
#pragma comment(lib,"ws2_32")
class CInitSock
{
public:
CInitSock(BYTE minorVer=2,BYTE majorVer=2)
{
WSADATA wsaData;
WORD sockVersion=MAKEWORD(minorVer,majorVer);
if (WSAStartup(sockVersion,&wsaData)!=0)
{
exit(0);
}
if ( LOBYTE( wsaData.wVersion ) != minorVer || HIBYTE( wsaData.wVersion ) != majorVer )
{
WSACleanup( );
exit(0);
}
}
~CInitSock()
{
::WSACleanup();
}
};
#include "CInitSocket.h"
#include <iostream>
#define WM_SOCKET WM_USER+1
LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
CInitSock initsock;
using namespace std;
int main()
{
char szClassName[]="king";
//创建窗口类
WNDCLASSEX wndclass;
wndclass.cbSize=sizeof(WNDCLASSEX);
wndclass.cbClsExtra=0;
wndclass.cbWndExtra=0;
wndclass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);
wndclass.hIcon=LoadIcon(NULL,IDI_APPLICATION);
wndclass.hInstance=NULL;
wndclass.lpfnWndProc=WindowProc;
wndclass.lpszClassName=szClassName;
wndclass.lpszMenuName=NULL;
wndclass.style=CS_HREDRAW | CS_VREDRAW;
wndclass.hIconSm=NULL;
//注册窗口类
RegisterClassEx(&wndclass);
//创建主窗口
HWND hWnd=CreateWindowEx(0,
"king",
"",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
NULL,
NULL);
if (NULL==hWnd)
{
MessageBox(NULL,"创建窗口出错!","error",MB_OK);
return -1;
}
USHORT nPort=4567;
SOCKET ListenSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in addrin;
addrin.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrin.sin_family=AF_INET;
addrin.sin_port=nPort;
if (SOCKET_ERROR==bind(ListenSocket,(sockaddr*)&addrin,sizeof(sockaddr)))
{
cout<<"监听失败! \n";
return -1;
}
//将套接字设为窗口桃子类型
WSAAsyncSelect(ListenSocket,hWnd,WM_SOCKET,FD_ACCEPT | FD_CLOSE);
listen(ListenSocket,5);
//从消息队列中取出消息
MSG msg;
while (GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch(uMsg) //确定是哪类消息
{
case WM_SOCKET:
{
SOCKET sock=wParam; //取得有事件发生的套接字句柄
//查看是否出错
if (WSAGETSELECTERROR(lParam)) //#define WSAGETSELECTERROR(lParam) HIWORD(lParam)
{
closesocket(sock);
return 0;
}
//处理发生的事件
switch(WSAGETSELECTEVENT(lParam)) //#define WSAGETSELECTEVENT(lParam) LOWORD(lParam)
{
case FD_ACCEPT: //监听中的套接字检查到有连接进入
{
SOCKET NewSock=accept(sock,NULL,NULL); //这里只作为演示,不保留地址什么的
WSAAsyncSelect(NewSock,hWnd,WM_SOCKET,FD_READ | FD_WRITE | FD_CLOSE);
}break;
case FD_WRITE:
{
//do something
}break;
case FD_READ:
{
char szText[]={0};
if (SOCKET_ERROR==recv(sock,szText,1024,0))
{
closesocket(sock);
}
else
{
cout<<"接受数据:"<<szText<<endl;
}
}break;
case FD_CLOSE:
{
closesocket(sock);
}break;
}
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}