以代话框模式建立 MFC 工程,源码如下: IShoeSimulatorDlg.h // IShoeSimulatorDlg.h : header file // #if !defined(AFX_ISHOESIMULATORDLG_H__74DA1E31_B7DE_4B40_8FDA_F4FC5325870C__INCLUDED_) #define AFX_ISHOESIMULATORDLG_H__74DA1E31_B7DE_4B40_8FDA_F4FC5325870C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // CIShoeSimulatorDlg dialog #define IDD_ISHOESIMULATOR_DIALOG 102 #define NETWORK_EVENT WM_USER+166 #define CLNT_MAX_NUM 100 class CIShoeSimulatorDlg : public CDialog { // Construction public: public: map<SOCKET, SOCKET> m_mapClientSocket; //存储与客户端通信的Socket的数组 /*各种网络异步事件的处理函数*/ void OnClose(SOCKET CurSock); //对端Socket断开 void OnSend(SOCKET CurSock); //发送网络数据包 void OnReceive(SOCKET CurSock); //网络数据包到达 void OnAccept(SOCKET CurSock); //客户端连接请求 BOOL InitNetwork(); //初始化网络函数 void OnNetEvent(WPARAM wParam, LPARAM lParam); //异步事件回调函数 void ReadINI(); CIShoeSimulatorDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CIShoeSimulatorDlg) enum { IDD = IDD_ISHOESIMULATOR_DIALOG }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CIShoeSimulatorDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CIShoeSimulatorDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnClear(); afx_msg void OnSend(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_nPort; string m_strAddr; SOCKET m_ServerSock; SOCKET m_clientSock; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ISHOESIMULATORDLG_H__74DA1E31_B7DE_4B40_8FDA_F4FC5325870C__INCLUDED_) IShoeSimulatorDlg.cpp // IShoeSimulatorDlg.cpp : implementation file // #include "stdafx.h" #include "IShoeSimulator.h" #include "IShoeSimulatorDlg.h" #include <afxsock.h> // MFC socket extensions #include <string> #include <vector> #include <map> #include <winsock.h> using namespace std; using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIShoeSimulatorDlg dialog CIShoeSimulatorDlg::CIShoeSimulatorDlg(CWnd* pParent /*=NULL*/) : CDialog(CIShoeSimulatorDlg::IDD, pParent) { //{{AFX_DATA_INIT(CIShoeSimulatorDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CIShoeSimulatorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CIShoeSimulatorDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CIShoeSimulatorDlg, CDialog) //{{AFX_MSG_MAP(CIShoeSimulatorDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDCLEAR, OnClear) ON_BN_CLICKED(ID_SEND, OnSend) ON_MESSAGE(NETWORK_EVENT, OnNetEvent) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIShoeSimulatorDlg message handlers BOOL CIShoeSimulatorDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here ReadINI(); if ( !InitNetwork() ) { AfxMessageBox(_T("Fail to Initial Socket!")); } m_mapClientSocket.clear(); return TRUE; // return TRUE unless you set the focus to a control } void CIShoeSimulatorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CIShoeSimulatorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CIShoeSimulatorDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CIShoeSimulatorDlg::OnClear() { SetDlgItemText(IDC_EDIT, ""); } BOOL CIShoeSimulatorDlg::InitNetwork() { return TRUE; } void CIShoeSimulatorDlg::ReadINI() { char szPath[256]; ::GetCurrentDirectory(256, szPath); strcat(szPath, "//AddrPort.ini"); char szHost[32]; memset( szHost, 0x00, sizeof(szHost) ); GetPrivateProfileString("listen","Host","",szHost,sizeof(szHost),szPath); m_nPort = GetPrivateProfileInt("listen","Port",10000,szPath); m_strAddr = szHost; } void CIShoeSimulatorDlg::OnNetEvent(WPARAM wParam, LPARAM lParam) { // 调用Winsock API函数,得到网络事件类型 int iEvent = WSAGETSELECTEVENT(lParam); //调用Winsock API函数,得到发生此事件的客户端套接字 SOCKET CurSock= (SOCKET)wParam; switch(iEvent) { case FD_ACCEPT: //客户端连接请求事件 OnAccept(CurSock); break; case FD_CLOSE: //客户端断开事件: OnClose(CurSock); break; case FD_READ: //网络数据包到达事件 OnReceive(CurSock); break; case FD_WRITE: //发送网络数据事件 OnSend(CurSock); break; default: break; } } void CIShoeSimulatorDlg::OnAccept(SOCKET CurSock) { // 接受连接请求,并保存与发起连接请求的客户端进行通信Socket // 为新的socket注册异步事件,注意没有Accept事件 m_mapClientSocket.insert(pair<SOCKET, SOCKET>(CurSock,CurSock)); } void CIShoeSimulatorDlg::OnClose(SOCKET CurSock) { // 结束与相应的客户端的通信,释放相应资源 map<SOCKET, SOCKET>::iterator iter = m_mapClientSocket.find(CurSock); if ( iter->first == CurSock ) { closesocket(iter->first); m_mapClientSocket.erase(iter); } } void CIShoeSimulatorDlg::OnSend(SOCKET CurSock) { // 在给客户端发数据时做相关预处理 } void CIShoeSimulatorDlg::OnReceive(SOCKET CurSock) { // 读出网络缓冲区中的数据包 } void CIShoeSimulatorDlg::OnSend() { char strbuf[2048]; GetDlgItemText(IDC_EDIT, strbuf, 2048 ); WSADATA wsaData; //指向WinSocket信息结构的指针 SOCKET sockListener; SOCKADDR_IN sin,saUdpServ; BOOL fBroadcast = TRUE; int nSize; if( WSAStartup(MAKEWORD(1, 1), &wsaData ) != 0 )//进行WinSocket的初始化 { AfxMessageBox("Can't initiates windows socket! Program stop./n");//初始化失败返回-1 return; } sockListener = socket( PF_INET, SOCK_DGRAM, 0 ); setsockopt( sockListener, SOL_SOCKET, SO_BROADCAST, (CHAR*)&fBroadcast, sizeof(BOOL) ); sin.sin_family = AF_INET; sin.sin_port = htons(0); sin.sin_addr.s_addr = htonl(INADDR_ANY); if( bind(sockListener, (SOCKADDR*)&sin, sizeof(sin)) != 0 ) { AfxMessageBox("Can't bind socket to local port! Program stop."); return; } saUdpServ.sin_family = AF_INET; saUdpServ.sin_addr.s_addr = htonl(INADDR_BROADCAST); saUdpServ.sin_port = htons(4003); nSize = sizeof(SOCKADDR_IN); if ( sendto( sockListener, strbuf, lstrlen(strbuf), 0, (SOCKADDR*)&saUdpServ, sizeof(SOCKADDR_IN)) ) { AfxMessageBox("Send fail!"); } else { CString str; str.Format(_T("%s"), strbuf); AfxMessageBox(str); } }