c++ mfc tcp client

1 New dialog box project ClientDemo

2 Create a new class CClientSocket and let it inherit from CSocket

#pragma once
#include <afxsock.h>
#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 Add dialog resources, add the corresponding class 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 Add member variables in CClientDemoApp

CString m_Name;
	CClientSocket m_clientSock;

5. Implement the connection server 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 Implement the client to send messages 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("发送错误"));

		}
	}
}

 

Guess you like

Origin blog.csdn.net/dxm809/article/details/114336868