c++ mfc tcp client

1 新建对话框工程ClientDemo

2 新建类CClientSocket,让其继承与CSocket

#pragma once
#include 
#include "CChatDlg.h"
class CClientSocket :
    public CSocket
{
public:
    ~CClientSocket();
public:
    CChatDlg* m_pChatDlg;

    void SetWnd(CChatDlg* pDlg);

    virtual void OnReceive(int nErrorCode);
};

#include "pch.h"
#include "CClientSocket.h"

CClientSocket::~CClientSocket()
{
	delete m_pChatDlg;
}

void CClientSocket::SetWnd(CChatDlg* pDlg)
{
	m_pChatDlg = pDlg;
}


void CClientSocket::OnReceive(int nErrorCode)
{
	// TODO: 在此添加专用代码和/或调用基类
	if (m_pChatDlg)
	{
		char bufferData[2048];
		CString str;
		int len = Receive(bufferData, 2048);
		if (len!=-1)
		{
			bufferData[len] = '\0';
			bufferData[len + 1] = '\0';
			str.Format(_T("%s"), bufferData);
			m_pChatDlg->m_list.AddString(str);
		}
	}

	CSocket::OnReceive(nErrorCode);
}

 

3 添加对话框资源,添加对应的类CChatDlg

CListBox m_list;
	CString m_sSend;
;
void CChatDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	CString sInfo;
	int len;
	UpdateData();
	if (m_sSend.IsEmpty())
	{
		AfxMessageBox(_T("发送内容不能为空"));
		
	}
	else
	{
		sInfo.Format(_T("%s说:%s"), theApp.m_Name, m_sSend);
		len = theApp.m_clientSock.Send(sInfo.GetBuffer(sInfo.GetLength()), 2 * sInfo.GetLength());
		if (SOCKET_ERROR==len)
		{
			AfxMessageBox(_T("发送错误"));

		}
	}
}

 4 在CClientDemoApp添加成员变量

CString m_Name;
	CClientSocket m_clientSock;

5.实现连接服务器CClientDemoDlg::OnBnClickedButton1()

void CClientDemoDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	CString sIP, sPort;
	UINT port;
	UpdateData();
	if (m_ip.IsBlank()||m_nServerPort<1024||m_nickName.IsEmpty())
	{
		AfxMessageBox(_T("请设置服务器信息"));
		return;
	}
	BYTE nf1, nf2, nf3, nf4;
	m_ip.GetAddress(nf1, nf2, nf3, nf4);
	sIP.Format(_T("%d.%d.%d.%d"), nf1, nf2, nf3, nf4);
	theApp.m_Name = m_nickName;
	if (theApp.m_clientSock.Connect(sIP,m_nServerPort))
	{
		AfxMessageBox(_T("连接服务器成功"));
		CChatDlg dlg;
		theApp.m_clientSock.SetWnd(&dlg);
		dlg.DoModal();
	}
	else
	{
		AfxMessageBox(_T("连接服务器失败"));
	}
}

 

5 实现客户端发送消息CChatDlg::OnBnClickedButton1()

void CChatDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	CString sInfo;
	int len;
	UpdateData();
	if (m_sSend.IsEmpty())
	{
		AfxMessageBox(_T("发送内容不能为空"));
		
	}
	else
	{
		sInfo.Format(_T("%s说:%s"), theApp.m_Name, m_sSend);
		len = theApp.m_clientSock.Send(sInfo.GetBuffer(sInfo.GetLength()), 2 * sInfo.GetLength());
		if (SOCKET_ERROR==len)
		{
			AfxMessageBox(_T("发送错误"));

		}
	}
}

 

你可能感兴趣的:(C++)