MFC tcpclient

CtcpClient.h

cpp 复制代码
#pragma once
#include<string>
using namespace std;
class CtcpClient
{
public:
	CtcpClient(void);
	~CtcpClient(void);
public:
	SOCKET m_socket;//socket句柄
	SOCKADDR_IN m_addrServer;//服务端地址
	WSADATA wsaData;
	SOCKADDR_IN addrServer;//服务端地址
	string m_strIP;//IP地址
	int m_intPort;//端口

	public:
	bool CtcpClient::InitClient(string p_strIP , int p_intPort);//初始化
	bool ConnectToServer();//连接
	bool CtcpClient::SendToServer(string p_str);//发送数据
	bool CtcpClient::RecvFromServer(string &p_strRecv);//接收数据
};

CtcpClient.h.cpp

cpp 复制代码
#include "StdAfx.h"
#include "CtcpClient.h"


CtcpClient::CtcpClient(void)
{
	m_socket = NULL;
}


CtcpClient::~CtcpClient(void)
{
	if(m_socket)
	{
		closesocket(m_socket);
	}
}

bool CtcpClient::InitClient(string p_strIP , int p_intPort)
{
	m_strIP = p_strIP;
	m_intPort = p_intPort;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	//定义要连接的服务端地址
	addrServer.sin_addr.S_un.S_addr = inet_addr(p_strIP.c_str());//目标IP(127.0.0.1是回送地址)
	addrServer.sin_family = AF_INET;
	addrServer.sin_port = htons(p_intPort);//连接端口6000
	//新建客户端socket
	m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(m_socket==NULL)
	{
		return false;
	}
	bool ret = ConnectToServer();
	return ret;
}
bool CtcpClient::ConnectToServer()
{
	m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(m_socket==NULL)
	{
		return false;
	}
	int ret = connect(m_socket, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));
	if(ret ==-1)
	{
		return false;
	}
	return true;
}
bool CtcpClient::SendToServer(string p_str)
{
	int nSend = send(m_socket,p_str.c_str(),p_str.length(),0);
	if (nSend > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}
bool CtcpClient::RecvFromServer(string &p_strRecv)
{
	char buffer[1024] = {0};
	int nRecv  = recv(m_socket,buffer, sizeof(buffer) , 0 );
	if(nRecv<=0)
	{
		return false;
	}
	else
	{
		buffer[nRecv] = '\0';
		p_strRecv  = buffer;
	}
	return true;
}
cpp 复制代码
// CenterControlDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "CenterControl.h"
#include "CenterControlDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif
 #define WM_SOCKET WM_USER+100

// 用于应用程序"关于"菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CCenterControlDlg 对话框




CCenterControlDlg::CCenterControlDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CCenterControlDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCenterControlDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CCenterControlDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_MESSAGE(WM_SOCKET,OnSocket)
	ON_BN_CLICKED(IDC_BUTTON1, &CCenterControlDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CCenterControlDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CCenterControlDlg::OnBnClickedButton3)
END_MESSAGE_MAP()


// CCenterControlDlg 消息处理程序

BOOL CCenterControlDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标
	m_sendEdit = (CEdit*)GetDlgItem(IDC_SEND_EDIT);
	m_chatEdit = (CEdit*)GetDlgItem(IDC_CHAT_EDIT);

	//if(true == m_client.InitClient("127.0.0.1" , 9999))
	//{
	//	LogMessage(_T("服务器连接成功"));
	//}
	//else
	//{
	//	LogMessage(_T("服务器断开连接"));
	//}
	
	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

//接受线程
UINT ServerCommunicationThread(LPVOID pParam)
{
	CCenterControlDlg* pDlg = (CCenterControlDlg*)pParam;
	char buffer[1024] = {0};
	string t_strRecv;
	while(1)
	{
		bool ret = pDlg->m_client.RecvFromServer(t_strRecv);
		if(ret)
		{
			if(t_strRecv.length()>0)
			{
				pDlg->LogMessage((CString)t_strRecv.c_str()+_T("<----server"));
			}
		}
	}
	return 0;
}


LRESULT CCenterControlDlg::OnSocket(WPARAM wParam, LPARAM lParam)
{
	CString str13;
	char cs[100] = { 0 };
	switch (lParam)
	{

	case FD_ACCEPT:
		LogMessage(_T("FD_ACCEPT"));
		break;

	case FD_READ:
		{
			char buffer[1024] = {0};
			string t_strRecv;
			bool ret = m_client.RecvFromServer(t_strRecv);
			if(ret)
			{
				if(t_strRecv.length()>0)
				{
					LogMessage((CString)t_strRecv.c_str()+_T("<----server"));
				}
			}
		}
		
		break;   
	case  FD_WRITE :
		LogMessage(_T("FD_WRITE"));
		break;

	}
	return true;
}

void CCenterControlDlg::OnBnClickedButton1()
{
	if(true == m_client.InitClient("127.0.0.1" , 9999))
	{
		LogMessage(_T("服务器连接成功"));
	}
	else
	{
		LogMessage(_T("服务器断开连接"));
	}
	::WSAAsyncSelect(m_client.m_socket,this->m_hWnd,WM_SOCKET,FD_ACCEPT|FD_READ);
	//AfxBeginThread(ServerCommunicationThread, this);
}
void CCenterControlDlg::LogMessage(const CString& message)
{
	CTime currentTime = CTime::GetCurrentTime();
	CString timeStr = currentTime.Format(_T(" [ %Y-%m-%d %H:%M:%S ]"));
	m_chatLog += timeStr + _T(" ") + message + _T("\r\n");
	m_chatEdit->SetWindowText(m_chatLog);
	int nline=m_chatEdit-> GetLineCount();
	m_chatEdit-> LineScroll(nline-1);
}

void CCenterControlDlg::OnBnClickedButton2()
{
	CString t_cstrSend;
	m_sendEdit->GetWindowTextW(t_cstrSend);
	string t_strSend = (CT2A)t_cstrSend;
	if(true == m_client.SendToServer(t_strSend))
	{
		LogMessage(t_cstrSend+_T("----> server"));
	}
	else
	{
		LogMessage(_T("发送失败"));
	}
}


void CCenterControlDlg::OnBnClickedButton3()
{
	AfxBeginThread(ServerCommunicationThread, this);
}

void CCenterControlDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

void CCenterControlDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文
		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		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;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CCenterControlDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}
相关推荐
sjyioo20 分钟前
【C++】类和对象.1
c++
arriettyandray41 分钟前
MFC/C++学习系列之简单记录——序列化机制
mfc
煤泥做不到的!1 小时前
挑战一个月基本掌握C++(第六天)了解函数,数字,数组,字符串
开发语言·c++
智能与优化1 小时前
C++打造局域网聊天室第十一课: 程序关闭及线程的结束
开发语言·c++
小王爱吃月亮糖2 小时前
C++进阶-1-单继承、多继承、虚继承
开发语言·c++·笔记·学习·visual studio
Am心若依旧4092 小时前
[c++进阶(三)]单例模式及特殊类的设计
java·c++·单例模式
小王爱吃月亮糖2 小时前
补充--C++的项目结构和管理
数据结构·c++·笔记·学习
因特麦克斯2 小时前
如何实现对象的克隆?如何实现单例模式?
c++·单例模式
Crazy learner4 小时前
C 和 C++ 动态库的跨语言调用原理
c语言·c++
金士顿6 小时前
MFC 文档模板 每个文档模板需要实例化吧
c++·mfc