通过QT进行服务器和客户端之间的网络通信

客户端

client.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T14:11:20
#
#-------------------------------------------------QT       += core gui network   #网络通信greaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = client
TEMPLATE = app# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += main.cpp\widget.cppHEADERS  += widget.hFORMS    += widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpSocket>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();void InitClient();private slots:void on_connect_bt_clicked();void on_send_bt_clicked();void OnReadData();private:Ui::Widget *ui;QTcpSocket *m_pSocket;
};#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.InitClient();w.show();return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>          //Qt 提供的输出调试信息的工具。
#include <QHostAddress>Widget::Widget(QWidget *parent) :   //Widget类继承自QWidgetQWidget(parent),ui(new Ui::Widget) //通过ui对象初始化界面布局
{ui->setupUi(this);m_pSocket = NULL;     //初始化m_pSocket为NULL
}Widget::~Widget()      //析构函数释放了ui对象。
{delete ui;
}void Widget::InitClient()       //设置界面初始状态,创建串口对象
{qDebug() << "Widget::InitClient() enter";if (NULL == m_pSocket){m_pSocket = new QTcpSocket(this);   //QTcpSocket是Qt提供的用于TCP网络通信的类connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(OnReadData()));//readyRead()当socket接收到新的数据时发出的信号,SIGNAL()是一个宏,将信号转换为字符串形式。this是信号的发送者。//当m_pSocket对象接收到数据时,会触发readyRead()信号,然后调用当前类的OnReadData()槽函数来处理这些接收到的数据}qDebug() << "Widget::InitClient() exit";
}void Widget::on_connect_bt_clicked()   //当按钮connect_bt被点击时触发
{qDebug() << "Widget::on_connect_bt_clicked() enter";QString strIP = ui->ip_edit->text();   //获取用户输入的IP地址QString strPort = ui->port_edit->text();qDebug() << strIP << " " << strPort;if (strIP.length() == 0 || strPort.length() == 0)  //检查用户输入的有效性,如果IP或端口号为空,则输出错误信息并返回{qDebug() << "input error";return;}if (NULL == m_pSocket)      //检查m_pSocket是否为NULL,如果是则输出错误信息并返回{qDebug() << "socket error";return;}m_pSocket->connectToHost(QHostAddress("127.0.0.1"), strPort.toShort());//使用m_pSocket->connectToHost()连接到指定的主机地址(这里是本地地址 "127.0.0.1")和端口号if (m_pSocket->waitForConnected(3000))//使用m_pSocket->waitForConnected(3000)等待连接建立,超时时间为3000毫秒(3秒){qDebug() << "connect ok";}else{qDebug() << "connect error";}qDebug() << "Widget::on_connect_bt_clicked() exit";
}void Widget::on_send_bt_clicked()
{qDebug() << "Widget::on_send_bt_clicked() enter";QString strData = ui->send_edit->text();if (strData.length() == 0){qDebug() << "input error";return;}if (NULL == m_pSocket){qDebug() << "socket error";return;}m_pSocket->write(strData.toStdString().data());    //发送字符串形式的数据到已连接的服务器端qDebug() << "Widget::on_send_bt_clicked() exit";
}void Widget::OnReadData()
{QByteArray arr = m_pSocket->readAll();    //读取所有接收到的数据,并将其存储arr中qDebug() << arr;
}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>Widget</class><widget class="QWidget" name="Widget"><property name="geometry"><rect><x>0</x><y>0</y><width>692</width><height>468</height></rect></property><property name="windowTitle"><string>Widget</string></property><widget class="QLabel" name="label"><property name="geometry"><rect><x>50</x><y>60</y><width>72</width><height>15</height></rect></property><property name="text"><string>ip</string></property></widget><widget class="QLineEdit" name="ip_edit"><property name="geometry"><rect><x>100</x><y>60</y><width>181</width><height>21</height></rect></property></widget><widget class="QLabel" name="label_2"><property name="geometry"><rect><x>40</x><y>100</y><width>72</width><height>15</height></rect></property><property name="text"><string>port</string></property></widget><widget class="QLineEdit" name="port_edit"><property name="geometry"><rect><x>100</x><y>100</y><width>181</width><height>21</height></rect></property></widget><widget class="QPushButton" name="connect_bt"><property name="geometry"><rect><x>350</x><y>90</y><width>93</width><height>28</height></rect></property><property name="text"><string>connect</string></property></widget><widget class="QPushButton" name="send_bt"><property name="geometry"><rect><x>350</x><y>150</y><width>93</width><height>28</height></rect></property><property name="text"><string>send</string></property></widget><widget class="QLineEdit" name="send_edit"><property name="geometry"><rect><x>100</x><y>160</y><width>181</width><height>21</height></rect></property></widget></widget><layoutdefault spacing="6" margin="11"/><resources/><connections/>
</ui>

服务器

server.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T09:20:48
#
#-------------------------------------------------QT       += core gui networkgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = server
TEMPLATE = app# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += main.cpp\widget.cppHEADERS  += widget.hFORMS    += widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();void InitServer();private slots:void OnNewConnection();void OnReadyData();void on_listen_bt_clicked();private:Ui::Widget *ui;QTcpServer *m_pServer;
};#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.InitServer();w.show();return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QHostAddress>
#include <QTcpSocket>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);m_pServer = NULL;
}Widget::~Widget()
{delete ui;
}void Widget::InitServer()
{qDebug() << "Widget::InitServer() enter";if (NULL == m_pServer){m_pServer = new QTcpServer(this);connect(m_pServer, SIGNAL(newConnection()), this, SLOT(OnNewConnection()));}qDebug() << "Widget::InitServer() exit";
}void Widget::OnNewConnection()
{qDebug() << "new connection";QTcpSocket *pTmp = m_pServer->nextPendingConnection();  //获取下一个挂起的连接if (NULL != pTmp){connect(pTmp, SIGNAL(readyRead()), this, SLOT(OnReadyData()));//当这个客户端socket有数据可读时,就会调用OnReadyData()函数}
}void Widget::OnReadyData()
{qDebug() << "read data";QTcpSocket *pTmp = (QTcpSocket *)sender();   //获取信号的发送者if (NULL == pTmp){qDebug() << "socket error";return;}QByteArray arr = pTmp->readAll();  //读取所有接收到的数据//qDebug() << arr;QString strData = ui->textEdit->toPlainText();  //将接收到的数据显示在界面中strData.append("recv : ");  //追加数据recv :strData.append(arr);strData.append("\n");ui->textEdit->setText(strData);pTmp->write(arr);   //将接收到的数据原样发送回客户端
}void Widget::on_listen_bt_clicked()
{qDebug() << "Widget::on_listen_bt_clicked() enter";if (NULL == m_pServer){return;}QString strIP = ui->ip_edit->text();QString strPort = ui->port_edit->text();if (strIP.length() == 0 || strPort.length() == 0){qDebug() << "input error";return;}bool bRet = m_pServer->listen(QHostAddress(strIP), strPort.toShort());   //监听指定的IP地址和端口号if (bRet == true){qDebug() << "server listen ok";}qDebug() << "Widget::on_listen_bt_clicked() enter";
}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>Widget</class><widget class="QWidget" name="Widget"><property name="geometry"><rect><x>0</x><y>0</y><width>893</width><height>629</height></rect></property><property name="windowTitle"><string>Widget</string></property><widget class="QLabel" name="label"><property name="geometry"><rect><x>80</x><y>60</y><width>72</width><height>15</height></rect></property><property name="text"><string>ip</string></property></widget><widget class="QLineEdit" name="ip_edit"><property name="geometry"><rect><x>140</x><y>60</y><width>221</width><height>21</height></rect></property></widget><widget class="QLineEdit" name="port_edit"><property name="geometry"><rect><x>140</x><y>100</y><width>221</width><height>21</height></rect></property></widget><widget class="QLabel" name="label_2"><property name="geometry"><rect><x>80</x><y>100</y><width>72</width><height>15</height></rect></property><property name="text"><string>port</string></property></widget><widget class="QPushButton" name="listen_bt"><property name="geometry"><rect><x>400</x><y>100</y><width>93</width><height>28</height></rect></property><property name="text"><string>listen</string></property></widget><widget class="QTextEdit" name="textEdit"><property name="geometry"><rect><x>60</x><y>190</y><width>761</width><height>401</height></rect></property></widget></widget><layoutdefault spacing="6" margin="11"/><resources/><connections/>
</ui>

测试

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/874439.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Docker安装nacos(详细教程)

Nacos 是一个开源的动态服务发现、配置管理和服务管理平台&#xff0c;广泛用于微服务架构中。在本文章中&#xff0c;博主将详细介绍如何使用 Docker 来安装 Nacos&#xff0c;以便快速启动并运行这个强大的服务管理工具。 前置条件 在开始安装 Nacos 之前&#xff0c;请确保…

解决union all之后字段返回非该字段类型的值

首先明确一个概念&#xff0c;union all的两部分的结果表的字段必须名称&#xff0c;类型&#xff0c;位置的先后都完全一样才可以 我的错误&#xff1a;一个datetime类型的字段&#xff0c;单独查询没问题&#xff0c;union all之后却返回了0 原因&#xff1a;字段顺序问题 …

DP(7) | 打家劫舍① | Java | LeetCode 198, 213, 337 做题总结

打家劫舍问题 来源于代码随想录&#xff1a;https://programmercarl.com/0198.%E6%89%93%E5%AE%B6%E5%8A%AB%E8%88%8D.html#%E6%80%9D%E8%B7%AF ① 确定dp数组&#xff08;dp table&#xff09;以及下标的含义 dp[i]&#xff1a;考虑下标i&#xff08;包括i&#xff09;以内的房…

pytorch 笔记:torch.optim.Adam

torch.optim.Adam 是一个实现 Adam 优化算法的类。Adam 是一个常用的梯度下降优化方法&#xff0c;特别适合处理大规模数据集和参数的深度学习模型 torch.optim.Adam(params, lr0.001, betas(0.9, 0.999), eps1e-08, weight_decay0, amsgradFalse, *, foreachNone, maximizeFa…

配置阿里云

ubuntu 20.04 设置国内镜像源&#xff08;阿里源、清华源&#xff09;_ubuntu 20.04 镜像源-CSDN博客 参考 sudo cp /etc/apt/sources.list /etc/apt/sources.list.back vim /etc/apt/sources.list sudo apt update sudo apt upgrade阿里云Ubuntu镜像&#xff1a;https://d…

I2C总线二级外设驱动开发(函数和代码详解)

I2C总线二级外设驱动开发是一个涉及多个步骤和函数调用的过程&#xff0c;主要目的是使得挂接在I2C总线上的外设能够正常工作。 一、I2C总线二级外设驱动开发概述 I2C总线是一种广泛使用的串行通信总线&#xff0c;用于连接微控制器及其外围设备。在Linux内核中&#xff0c;I2…

实验四 FPGA 使用Verilog HDL设计电机运动控制程序

实验目的 1.掌握使用GPIO控制直流电机的原理。 2.掌握使用Verilog HDL设计电机运动控制程序的方法。 实验要求 采用Verilog HDL语言设计直流电机运动控制程序&#xff0c;实现直流电机的运动控制&#xff0c;并通过数码管显示当前输出的PWM波的占空比。通过按键或拔位开关可…

ArcGIS Pro不能编辑ArcGIS10.X的注记的解决办法

​ 点击下方全系列课程学习 点击学习—>ArcGIS全系列实战视频教程——9个单一课程组合系列直播回放 点击学习——>遥感影像综合处理4大遥感软件ArcGISENVIErdaseCognition 一、问题 我们利用ArcGIS Pro编辑ArcGIS10.X系列软件生成的注记要素类的时候&#xff0c;会提示不…

Apache POI-Excel入门与实战

目录 一、了解Apache POI 1.1 什么是Apache POI 1.2 为什么要使用ApaChe POI 1.3 Apache POI应用场景 1.4 Apache POI 依赖 二、Apache POI-Excel 入门案例 2.1 写入Excel文件 2.2 读取文件 四、Apache POI实战 4.1 创建一个获取天气的API 4.2高德天气请求API与响应…

iphone11 如何打开开发者模式?

嗨&#xff0c;大家好&#xff0c;我是兰若姐姐。 今天有小伙伴在问&#xff0c;怎么打开ios手机的开发者模式&#xff0c;他需要做app自动化测试&#xff0c;他的手机是是iphone11&#xff0c;今天就把iphone11开发者打开的步骤给记录分享下 在电脑上安装 Xcode&#xff1a;开…

Sqlmap中文使用手册 - Techniques模块参数使用

目录 1. Techniques模块的帮助文档2. 各个参数的介绍2.1 --techniqueTECH2.2 --time-secTIMESEC2.3 --union-colsUCOLS2.4 --union-charUCHAR2.5 --union-fromUFROM2.6 --dns-domainDNS2.7 --second-urlSEC2.8 --second-reqSEC 1. Techniques模块的帮助文档 Techniques:These o…

怎样使用 Juicer tools 的 dump 命令将.hic文件转换为交互矩阵matrix计数文件 (Windows)

创作日志&#xff1a; 万恶的生信…一个scHiC数据集没有提供处理好的计数文件&#xff0c;需要从.hic转换。Github一个个好长的文档看了好久才定位到 juicer tools 的dump命令&#xff0c;使用起来比想象中简单。 一、下载Juicer tools 注意&#xff1a;使用Juicer tools的前提…

邮件安全篇:邮件反垃圾系统运作机制简介

1. 什么是邮件反垃圾系统&#xff1f; 邮件反垃圾系统是一种专门设计用于检测、过滤和阻止垃圾邮件的技术解决方案。用于保护用户的邮箱免受未经请求的商业广告、诈骗信息、恶意软件、钓鱼攻击和其他非用户意愿接收的电子邮件的侵扰。 反垃圾系统的常见部署形式 2. 邮件反垃圾…

Dubbo SPI 之路由器

1. 背景介绍 Dubbo 是一个高性能的 Java RPC 框架&#xff0c;由阿里巴巴开源并广泛应用于分布式系统中。在 Dubbo 的架构中&#xff0c;SPI&#xff08;Service Provider Interface&#xff09;是一个关键组件&#xff0c;允许在运行时动态加载不同的服务实现。SPI 机制提供了…

day6 io线程

获取终端输入的字符

深入探究 Golang 反射:功能与原理及应用

Go 出于通用性的考量&#xff0c;提供了反射这一功能。借助反射功能&#xff0c;我们可以实现通用性更强的函数&#xff0c;传入任意的参数&#xff0c;在函数内通过反射动态调用参数对象的方法并访问它的属性。举例来说&#xff0c;下面的bridge接口为了支持灵活调用任意函数&…

构建自动化的魔法:Gradle Build Init的深度解析

构建自动化的魔法&#xff1a;Gradle Build Init的深度解析 在软件开发过程中&#xff0c;自动化构建是提高效率和保证质量的关键。Gradle&#xff0c;作为一个强大的构建工具&#xff0c;提供了丰富的功能来帮助开发者自动化构建过程。其中&#xff0c;Gradle的构建配置包&am…

python一维表转二维表

一维表转二维表 import pandas as pd # 读取数据 product_df pd.read_csv(rD:\excelFile\practice\物品属性值一维表.csv,encodingutf-8) # print(product_df)# 将一维表转变二维 s pd.Series(list(product_df[属性值]),index[product_df[物品编号],product_df[属性名]]) …

【git】github中的Pull Request是什么

在 Git 中&#xff0c;"pull request"&#xff08;简称 PR&#xff09;是一种在分布式版本控制系统中使用的功能&#xff0c;特别是在使用 GitHub、GitLab、Bitbucket 等基于 Git 的代码托管平台时。Pull Request 允许开发者请求将他们的代码更改合并到另一个分支&am…

GMSSL2.x编译鸿蒙静态库和动态库及使用

一、编译环境准备 1.1 开发工具 DevEco-Studio下载。 1.2 SDK下载 ​ 下载编译第三方库的SDK有两种方式&#xff0c;第一种方式从官方渠道根据电脑系统选择对应的SDK版本&#xff0c;第二种方式通过DevEco-Studio下载SDK。本文只介绍通过DevEco-Studio下载SDK的方式。 安装…