MFC tcpclient

embedded/2024/10/30 20:12:21/

CtcpClient.h

#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

#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//新建客户端socketm_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;
}

// 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);
}

http://www.ppmy.cn/embedded/133694.html

相关文章

Spring MVC介绍

1.Spring MVC起步 1.1 Spring MVC的请求流程 请求的第一站是Spring的DispatcherServlet&#xff0c;Spring mvc所有的请求都会经过一个前端控制器Servlet&#xff0c;这个前端控制器就是DispatcherServlet。 DispatcherServlet将请求发送给Spring MVC控制器&#xff0c;这个控…

第5次CCF CSP认证真题解

1、数列分段 题目链接&#xff1a;https://sim.csp.thusaac.com/contest/5/problem/0 区分每一段的方法就是判断数列中的每一个数是否与前一个数相等。 100分代码&#xff1a; #include <iostream> using namespace std; int main(int argc, char *argv[]) {int n;ci…

2024前端JS面试题总汇

2024前端JS面试题总汇 1、JS数据类型有哪些&#xff1f;区别&#xff1f;⭐⭐⭐ js数据类型分为两大类&#xff0c;基本数据和引用数据类型&#xff0c;他们两个不同的原因是存储方式不同 基本数据类型&#xff1a;number&#xff0c;null&#xff0c;string&#xff0c;boole…

前端零基础入门到上班:【Day3】从零开始构建网页骨架HTML

HTML 基础入门&#xff1a;从零开始构建网页骨架 目录 1. 什么是 HTML&#xff1f;HTML 的核心作用 2. HTML 基本结构2.1 DOCTYPE 声明2.2 <html> 标签2.3 <head> 标签2.4 <body> 标签 3. HTML 常用标签详解3.1 标题标签3.2 段落和文本标签3.3 链接标签3.4 图…

Soanrquber集成Gitlab 之 导入Gitlab项目

集成Gitlab 之 导入Gitlab项目 说明&#xff1a; Sonarquber里面的项目&#xff0c;顺便设置&#xff0c;只要在集成CI的时候&#xff0c;使用这个项目的项目标识即可。 当然项目名称一一对应是最好的了&#xff0c;所以这里讲导入Gitlab的项目&#xff0c;项目名称一一对应&…

gin入门教程(10):实现jwt认证

使用 github.com/golang-jwt/jwt 实现 JWT&#xff08;JSON Web Token&#xff09;可以有效地进行用户身份验证,这个功能往往在接口前后端分离的应用中经常用到。以下是一个基本的示例&#xff0c;演示如何在 Gin 框架中实现 JWT 认证。 目录结构 /hello-gin │ ├── cmd/ …

openjdk17 hotspot JVM解析class文件

##openjdk17 hotspot JVM解析class文件 ClassFileParser::parse_stream 解析字节码 void ClassFileParser::parse_stream(const ClassFileStream* const stream,TRAPS) {assert(stream ! NULL, "invariant");assert(_class_name ! NULL, "invariant");//…

WebGL进阶(四)-视点和视线

理论基础&#xff1a; 顶点着色器 Vertex Shader 主要是负责处理顶点位置、顶点颜色、顶点向量等顶点的数据&#xff1b;处理一些顶点的变换&#xff1a;例如在进行视图变换和投影变换时MVP矩阵会改变顶点的位置信息。 输入&#xff1a; 顶点着色器输入部分主要是声明&…