码源:http://pan.baidu.com/s/1o6PQjou; 先打开server,再打开client,ip地址要去程序里去改
VS2010 新建project 选择MFC 选择MFC Application; 在application type选择dialog based选项;在advanced features页勾选windows sockets;finish。
删除OK;cancel按钮;在dialog窗口添加ListBox Control; Edit Control; 添加2个button control;分别命名为为 连接 发送。
添加类CClientSocket 继承CSocket;
//头文件clientsocket.h
public:
virtual void OnClose(int nErrorCode);
virtual void OnReceive(int nErrorCode);
CClientDlg *mClientDlg;
void GetDlg(CClientDlg *dlg);
//.cpp
void CClientSocket::GetDlg(CClientDlg *dlg)
{
mClientDlg = dlg;
}
void CClientSocket::OnClose(int nErrorCode)
{
mClientDlg->OnClose();
CSocket::OnClose(nErrorCode);
}
void CClientSocket::OnReceive(int nErrorCode)
{
mClientDlg->OnReceive();
CSocket::OnReceive(nErrorCode);
}
clientDlg.h
public:
CClientDlg(CWnd* pParent = NULL); // 标准构造函数
void OnReceive();
void OnClose();
void SocketReset();
CListBox m_listBox;
CButton m_sendBtn;
CEdit m_edit;
CIPAddressCtrl m_IPAddress;
afx_msg void OnBnClickedOk();
afx_msg void OnEnChangeEdit1();
private:
CClientSocket *m_ClientSocket;
CArchive *m_archiveIn;
CArchive *m_archiveOut;
CSocketFile *m_socketFile;
client.cpp
void CClientDlg::DoDataExchange(CDataExchange* pDX) //关联控件与定义的变量名
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST3, m_listBox);
DDX_Control(pDX,IDOK,m_sendBtn);
DDX_Control(pDX,IDC_EDIT1,m_edit);
DDX_Control(pDX,IDC_IPADDRESS1, m_IPAddress);
}
BOOL CClientDlg::OnInitDialog()
{
// TODO: 在此添加额外的初始化代码
m_ClientSocket = NULL;
m_socketFile = NULL;
m_archiveIn = NULL;
m_archiveOut = NULL;
m_ClientSocket = new CClientSocket;
m_ClientSocket->GetDlg(this);
CString str111;
//BYTE nFild1[4];
CString sIP1;
//UpdateData();
/*m_IPAddress.GetAddress(nFild1[0],nFild1[1],nFild1[2],nFild1[3]);
sIP1.Format((wchar_t *)"%d.%d.%d.%d",nFild1[0],nFild1[1],nFild1[2],nFild1[3]);*/
sIP1 = "localhost";
if (m_ClientSocket->Create())
{
if ( m_ClientSocket->Connect(sIP1, 5000) )
{
m_socketFile = new CSocketFile(m_ClientSocket);
m_archiveIn = new CArchive(m_socketFile, CArchive::load);
m_archiveOut = new CArchive(m_socketFile, CArchive::store);
str111 = "连接成功";
m_listBox.AddString(str111);
m_sendBtn.EnableWindow(TRUE);
}
else
{
str111 = "连接不成功";
m_listBox.AddString(str111);
delete m_ClientSocket;
}
}
else
{
str111 = "初始化失败";
m_listBox.AddString(str111);
delete m_ClientSocket;
}
return TRUE; //
}
void CClientDlg::OnReceive()
{
CString str;
CString str111;
str111 = "对方发来消息如下";
m_listBox.AddString(str111);
*m_archiveIn>>str;
m_listBox.AddString(str);
m_listBox.SetCurSel(m_listBox.GetCount()-1);
}
void CClientDlg::OnBnClickedOk()
{
CString str;
//str = _T("");
//str = "";
CString str111;
m_edit.GetWindowText(str);
//str = 'A';
if (str.GetLength() == 0)
{
str111 = "空信息,发不出去";
m_listBox.AddString(str111);
}
else
{
str111 = "你发的信息如下";
m_listBox.AddString(str111);
m_listBox.SetCurSel(m_listBox.GetCount()-1);
m_listBox.AddString(str);
m_listBox.SetCurSel(m_listBox.GetCount()-1);
*m_archiveOut<<str;
m_archiveOut->Flush();
}
}