MFC对Sockect的封装.docx
- 文档编号:23940255
- 上传时间:2023-05-22
- 格式:DOCX
- 页数:22
- 大小:394.83KB
MFC对Sockect的封装.docx
《MFC对Sockect的封装.docx》由会员分享,可在线阅读,更多相关《MFC对Sockect的封装.docx(22页珍藏版)》请在冰豆网上搜索。
MFC对Sockect的封装
MFC对Sockect的封装:
CSockect的继承关系:
CObject
CSyncSockect
CSockect
MFC对CSockect的封装采用如下步骤:
服务器
客户端
//构造一个CSockect对象sockect
CSockectsockSrvr;
//构造一个CSockect对象sockect
CSockectsockClient;
//生成sockect
sockSrvr.Create(nPort);
//生成sockect
sockClient.Create();
//进行监听
sockSrvr.Listen();
//实现链接
sockClient.Connect(strAddr,nPort)
//构造新的sockect
sockSrvr.Accept(sockRecv);
//构造文件对象
CSockFilefile(&sockRecv);
//构造文件对象
CSockFilefile(&sockClient);
//构造CArchive对象
CArchive.arIn(&file,CArchive:
:
load)
//构造CArchive对象
CArchive.arIn(&file,CArchive:
:
load)
//使用CArchive传送数据
arIn>>dwValue;
//使用CArchive传送数据
arIn>>dwValue;
具体代码实现实例:
非面向连接的SocketsMFC例子
1建立基于对话框的MFC工程Socketa,记住选择Sockect支持;
2设计一个对话框,用来设置IP地址
3添加类CsocketSer,选择基类为CAsyncSocket
相关函数代码如下:
SockectaDlg.cpp
//SockectaDlg.cpp:
implementationfile
#include"stdafx.h"
#include"Sockecta.h"
#include"IPSetDlg.h"
#include"SockectaDlg.h"
#ifdef_DEBUG
#definenewDEBUG_NEW
#undefTHIS_FILE
staticcharTHIS_FILE[]=__FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
//CAboutDlgdialogusedforAppAbout
classCAboutDlg:
publicCDialog
{
public:
CAboutDlg();
//DialogData
//{{AFX_DATA(CAboutDlg)
enum{IDD=IDD_ABOUTBOX};
//}}AFX_DATA
//ClassWizardgeneratedvirtualfunctionoverrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtualvoidDoDataExchange(CDataExchange*pDX);//DDX/DDVsupport
//}}AFX_VIRTUAL
//Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg:
:
CAboutDlg():
CDialog(CAboutDlg:
:
IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
voidCAboutDlg:
:
DoDataExchange(CDataExchange*pDX)
{
CDialog:
:
DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg,CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
//Nomessagehandlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
//CSockectaDlgdialog
CSockectaDlg:
:
CSockectaDlg(CWnd*pParent/*=NULL*/)
:
CDialog(CSockectaDlg:
:
IDD,pParent)
{
//{{AFX_DATA_INIT(CSockectaDlg)
//NOTE:
theClassWizardwilladdmemberinitializationhere
//}}AFX_DATA_INIT
//NotethatLoadIcondoesnotrequireasubsequentDestroyIconinWin32
m_hIcon=AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
voidCSockectaDlg:
:
DoDataExchange(CDataExchange*pDX)
{
CDialog:
:
DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSockectaDlg)
DDX_Control(pDX,IDC_LISTINFO,m_ctrlInfo);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSockectaDlg,CDialog)
//{{AFX_MSG_MAP(CSockectaDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_SET,OnSet)
ON_BN_CLICKED(IDC_SEND,OnSend)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
//CSockectaDlgmessagehandlers
BOOLCSockectaDlg:
:
OnInitDialog()
{
CDialog:
:
OnInitDialog();
//Add"About..."menuitemtosystemmenu.
//IDM_ABOUTBOXmustbeinthesystemcommandrange.
ASSERT((IDM_ABOUTBOX&0xFFF0)==IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX<0xF000);
CMenu*pSysMenu=GetSystemMenu(FALSE);
if(pSysMenu!
=NULL)
{
CStringstrAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if(!
strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING,IDM_ABOUTBOX,strAboutMenu);
}
}
//Settheiconforthisdialog.Theframeworkdoesthisautomatically
//whentheapplication'smainwindowisnotadialog
SetIcon(m_hIcon,TRUE);//Setbigicon
SetIcon(m_hIcon,FALSE);//Setsmallicon
GetDlgItem(IDC_SEND)->EnableWindow(FALSE);
GetDlgItem(IDC_SENDSTRING)->EnableWindow(FALSE);
SetDlgItemText(IDC_SENDSTRING,"jfd");
m_socketSer.SetHWnd((HWND)this);
intport=1601;
if(m_socketSer.Create(port,SOCK_DGRAM,FD_READ|FD_WRITE,NULL)==SOCKET_ERROR)
AfxMessageBox("创建接收Socket失败!
");
//TODO:
Addextrainitializationhere
returnTRUE;//returnTRUEunlessyousetthefocustoacontrol
}
voidCSockectaDlg:
:
OnSysCommand(UINTnID,LPARAMlParam)
{
if((nID&0xFFF0)==IDM_ABOUTBOX)
{
CAboutDlgdlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog:
:
OnSysCommand(nID,lParam);
}
}
//Ifyouaddaminimizebuttontoyourdialog,youwillneedthecodebelow
//todrawtheicon.ForMFCapplicationsusingthedocument/viewmodel,
//thisisautomaticallydoneforyoubytheframework.
voidCSockectaDlg:
:
OnPaint()
{
if(IsIconic())
{
CPaintDCdc(this);//devicecontextforpainting
SendMessage(WM_ICONERASEBKGND,(WPARAM)dc.GetSafeHdc(),0);
//Centericoninclientrectangle
intcxIcon=GetSystemMetrics(SM_CXICON);
intcyIcon=GetSystemMetrics(SM_CYICON);
CRectrect;
GetClientRect(&rect);
intx=(rect.Width()-cxIcon+1)/2;
inty=(rect.Height()-cyIcon+1)/2;
//Drawtheicon
dc.DrawIcon(x,y,m_hIcon);
}
else
{
CDialog:
:
OnPaint();
}
}
//Thesystemcallsthistoobtainthecursortodisplaywhiletheuserdrags
//theminimizedwindow.
HCURSORCSockectaDlg:
:
OnQueryDragIcon()
{
return(HCURSOR)m_hIcon;
}
voidCSockectaDlg:
:
OnSet()
{
//TODO:
Addyourcontrolnotificationhandlercodehere
CIPSetDlgipdlg;
if(ipdlg.DoModal()==IDOK)
{
m_strIPAddress=ipdlg.m_strIPAddress;
GetDlgItem(IDC_SEND)->EnableWindow(TRUE);
GetDlgItem(IDC_SENDSTRING)->EnableWindow(TRUE);
}
GetDlgItem(IDC_SEND)->SetFocus();
((CEdit*)GetDlgItem(IDC_SENDSTRING))->SetSel(0,-1);
GetDlgItem(IDC_SENDSTRING)->SetFocus();
}
voidCSockectaDlg:
:
OnSend()
{
//TODO:
Addyourcontrolnotificationhandlercodehere
intport;
CStringstrSend;
CAsyncSocket*psocketSend=newCAsyncSocket;
port=1600;
if(psocketSend->Create(port,SOCK_DGRAM,FD_READ|FD_WRITE,NULL)==SOCKET_ERROR)
{
AfxMessageBox("创建Socket失败!
");
deletepsocketSend;
return;
}
GetDlgItemText(IDC_SENDSTRING,strSend);
intnReault=psocketSend->SendTo(strSend,strSend.GetLength(),1601,m_strIPAddress);
if(SOCKET_ERROR==nReault)
{
AfxMessageBox("发送消息失败!
");
deletepsocketSend;
return;
}
else
{
CStringstring;
string="Send:
";
string+=strSend;
m_ctrlInfo.AddString(string);
string="Targetaddress:
";
string+=m_strIPAddress;
m_ctrlInfo.AddString(string);
:
:
SendMessage(m_ctrlInfo.GetSafeHwnd(),WM_VSCROLL,SB_BOTTOM,NULL);
}
deletepsocketSend;
((CEdit*)GetDlgItem(IDC_SENDSTRING))->SetSel(0,-1);
GetDlgItem(IDC_SENDSTRING)->SetFocus();
}
voidCSockectaDlg:
:
OnReceive()
{
charstrRecv[200];
CStringstrRecvIP;
UINTnRecvPort;
intnRes;
nRes=m_socketSer.ReceiveFrom(strRecv,sizeof(strRecv),strRecvIP,nRecvPort);
if((nRes!
=SOCKET_ERROR)&&(1600==nRecvPort))
{
CStringstring;
strRecv[nRes]='\0';
string="Receiveed:
";
string+=strRecv;
m_ctrlInfo.AddString(string);
string+="源IP地址:
";
string+=strRecvIP;
m_ctrlInfo.AddString(string);
:
:
SendMessage(m_ctrlInfo.GetSafeHwnd(),WM_VSCROLL,SB_BOTTOM,NULL);
}
}
SockectaDlg.h
//SockectaDlg.h:
headerfile
//
#if!
defined(AFX_SOCKECTADLG_H__992AFF45_91C9_4062_94DF_37775EC7F014__INCLUDED_)
#defineAFX_SOCKECTADLG_H__992AFF45_91C9_4062_94DF_37775EC7F014__INCLUDED_
#include"socketSer.h"
#if_MSC_VER>1000
#pragmaonce
#endif//_MSC_VER>1000
/////////////////////////////////////////////////////////////////////////////
//CSockectaDlgdialog
classCSockectaDlg:
publicCDialog
{
//Construction
public:
CsocketSerm_socketSer;
CStringm_strIPAddress;
voidOnReceive();
CSockectaDlg(CWnd*pParent=NULL);//standardconstructor
//DialogData
//{{AFX_DATA(CSockectaDlg)
enum{IDD=IDD_SOCKECTA_DIALOG};
CListBoxm_ctrlInfo;
//}}AFX_DATA
//ClassWizardgeneratedvirtualfunctionoverrides
//{{AFX_VIRTUAL(CSockectaDlg)
protected:
virtualvoidDoDataExchange(CDataExchange*pDX);//DDX/DDVsupport
//}}AFX_VIRTUAL
//Implementation
protected:
HICONm_hIcon;
//Generatedmessagemapfunctions
//{{AFX_MSG(CSockectaDlg)
virtualBOOLOnInitDialog();
afx_msgvoidOnSysCommand(UINTnID,LPARAMlParam);
afx_msgvoidOnPaint();
afx_msgHCURSOROnQueryDragIcon();
afx_msgvoidOnSet();
afx_msgvoidOnSend();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
//MicrosoftVisualC++willinsertadditionaldeclarationsimmediatelybeforethepreviousline.
#endif//!
defined(AFX_SOCKECTADLG_H__992AFF45_91C9_4062_94DF_37775EC7F014__INCLUDED_)
IPSetDlg.cpp
//IPSetDlg.cpp:
implementationfile
#include"stdafx.h"
#include"Sockecta.h"
#include"IPSetDlg.h"
#ifdef_DEBUG
#definenewDEBUG_NEW
#undefTHIS_FILE
staticcharTHIS_FILE[]=__FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
//CIPSetDlgdialog
CIPSetDlg:
:
CIPSetDlg(CWnd*pParent/*=NULL*/)
:
CDialog(CIPSetDlg:
:
IDD,pParent)
{
//{{AFX_DATA_INIT(CIPSetDlg)
m_strIPAddress=_T("");
//}}AFX_DATA_INIT
}
voidCIPSetDlg:
:
DoDataExchange(CDataExchange*pDX)
{
CDialog:
:
DoDataExchange(pDX);
//{{AFX_DATA_MAP(CIPSetDlg)
DDX_Text(pDX,IDC_IPADDRESS,m_strIPAddress);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CIPSetDlg,CDialog)
//{{AFX_MSG_MAP(CIPSetDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
//CIPSetDlgmessagehandlers
BOOLCIPSetDlg:
:
OnInitDialog()
{
CDialog:
:
OnInitDialog();
//TODO:
Addextrainitializationhere
((CEdit*)GetDlgItem(IDC_IPADDRESS))->SetSel(0,-1);
GetDlgItem(IDC_IPADDRESS)->SetFocus();
returnFALSE;//returnTRUEunlessyousetthefocustoacontrol
//EXCEPTION:
OCXPropertyPagesshouldreturnFALSE
}
IPSetDlg.h
#if!
defined(AFX_IPSETDLG_H__4187FAE9_B7AC_41E1_B081_8F5336DAE119__INCLUDED_)
#defineAFX_IPSETDLG_H__4187
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- MFC Sockect 封装