Qt TCP网络上位机的设计(通过网络编程与下位机结合)

news2025/5/23 9:18:19

目录

TCP 协议基础

QTcpServer 和 QAbstractSocket 主要接口函数

TCP 应用程序

1.服务端

2.客户端

上位机通过网络编程与下位机实现通信


TCP 协议基础

传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议

TCP 的拥塞控制算法(也称 AIMD 算法)。该算法主要包括四个主要部分:慢启动、拥塞避免、快速重传和快速恢复

TCP 通信必须建立 TCP 连接(客户端和服务器端),Qt 提供 QTcpSocket 类和 QTcpServer 类专门用于建立 TCP 通信程序。服务 器端用 QTcpServer 监听端口及建立服务器;QTcpSocket 用于建立 连接后使用套接字(socket)进行通信

QTcpServer 和 QAbstractSocket 主要接口函数

QTcpServer 是从 QOjbect 继承的类用于服务器建立网络监听, 创建网络 socket 连接。QTcpServer 主要接口函数如下:

QAbstractSocket主要接口函数如下:

TCP 应用程序

1.服务端

UI绘图:

代码示例:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include <QTcpServer> // 专门用于建立TCP连接并传输数据信息
#include <QtNetwork> // 此模块提供开发TCP/IP客户端和服务器的类

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;


    // 自定义如下
private:
    QTcpServer *tcpserver; //TCP服务器
    QTcpSocket *tcpsocket;// TCP通讯socket
    QString GetLocalIpAddress(); // 获取本机的IP地址

private slots:
    void clientconnect();
    void clientdisconnect();
    void socketreaddata();
    void newconnection();


    void on_pushButton_Start_clicked();
    void on_pushButton_Stop_clicked();
    void on_pushButton_Send_clicked();

protected:
    void closeEvent(QCloseEvent *event);

};
#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString strip=GetLocalIpAddress();
    // QMessageBox::information(this,"数据",strip,QMessageBox::Yes);

    ui->comboBoxIp->addItem(strip);


    tcpserver=new QTcpServer(this);

    connect(tcpserver,SIGNAL(newConnection()),this,SLOT(newconnection()));

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_Start_clicked()
{
    QString ip=ui->comboBoxIp->currentText();
    quint16 port=ui->spinBoxPort->value();

    QHostAddress address(ip);
    tcpserver->listen(address,port);

    ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$开始监听$$$$$$$$$$");
    ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$服务器地址$$$$$$$$$$:"+
                                               tcpserver->serverAddress().toString());
    ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$服务器端口$$$$$$$$$$:"+
                                               QString::number(tcpserver->serverPort()));
    ui->pushButton_Start->setEnabled(false);
    ui->pushButton_Stop->setEnabled(true);

}

void MainWindow::on_pushButton_Stop_clicked()
{
    if(tcpserver->isListening())
    {
        tcpserver->close();
        ui->pushButton_Start->setEnabled(true);
        ui->pushButton_Stop->setEnabled(false);
    }

}

void MainWindow::on_pushButton_Send_clicked()
{
    QString strmsg=ui->lineEdit_InputMsg->text();
    ui->plainTextEdit_DispMsg->appendPlainText("[out]:"+strmsg);

    ui->lineEdit_InputMsg->clear();

    QByteArray str=strmsg.toUtf8();
    str.append("\n");
    tcpsocket->write(str);
}


QString MainWindow::GetLocalIpAddress() // 获取本机的IP地址
{
    QString hostname=QHostInfo::localHostName();
    QHostInfo hostinfo=QHostInfo::fromName(hostname);

    QString localip="";

    QList<QHostAddress> addresslist=hostinfo.addresses();

    if(!addresslist.isEmpty())
    {
        for (int i=0;i<addresslist.count();i++)
        {
            QHostAddress addrhost=addresslist.at(i);
            if(QAbstractSocket::IPv4Protocol==addrhost.protocol())
            {
                localip=addrhost.toString();
                break;
            }

        }
    }

    return localip;
}

void MainWindow::clientconnect()
{
    // 客户端连接
    ui->plainTextEdit_DispMsg->appendPlainText("**********客户端socket连接**********");
    ui->plainTextEdit_DispMsg->appendPlainText("**********peer address:"+
                                               tcpsocket->peerAddress().toString());
    ui->plainTextEdit_DispMsg->appendPlainText("**********peer port:"+
                                               QString::number(tcpsocket->peerPort()));

}

void MainWindow::clientdisconnect()
{
    // 客户端断开连接
    ui->plainTextEdit_DispMsg->appendPlainText("**********客户端socket断开连接**********");
    tcpsocket->deleteLater();

}

void MainWindow::socketreaddata()
{
    // 读取数据
    while(tcpsocket->canReadLine())
        ui->plainTextEdit_DispMsg->appendPlainText("[in]"+tcpsocket->readLine());

}

void MainWindow::newconnection()
{
    tcpsocket=tcpserver->nextPendingConnection();

    connect(tcpsocket,SIGNAL(connected()),this,SLOT(clientconnect()));
    clientconnect();

    connect(tcpsocket,SIGNAL(disconnected()),this,SLOT(clientdisconnect()));

    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(socketreaddata()));

    connect(tcpsocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(OnSocketStateChanged(QAbstractSocket::SocketState)));


}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(tcpserver->isListening())
        tcpserver->close();

    event->accept();
}

2.客户端

UI绘图:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>


#include <QTcpSocket>
#include <QHostAddress>
#include <QHostInfo>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;


private:
    QTcpSocket *tcpclient; // 客户端tcpclient
    QString getlocalip(); // 获取本机IP地址

protected:
    void closeEvent(QCloseEvent *event);

private slots:
    void connectfunc();
    void disconnectfunc();
    void socketreaddata();





    void on_pushButton_Connect_clicked();
    void on_pushButton_Send_clicked();
    void on_pushButton_Disconnect_clicked();
};
#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpclient=new QTcpSocket(this);

    QString strip=getlocalip();

    ui->comboBoxIp->addItem(strip);


    connect(tcpclient,SIGNAL(connected()),this,SLOT(connectfunc()));
    connect(tcpclient,SIGNAL(disconnected()),this,SLOT(disconnectfunc()));
    connect(tcpclient,SIGNAL(readyRead()),this,SLOT(socketreaddata()));


}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_Connect_clicked()
{
    QString addr=ui->comboBoxIp->currentText();
    quint16 port=ui->spinBoxPort->value();
    tcpclient->connectToHost(addr,port);
}

void MainWindow::on_pushButton_Send_clicked()
{
    QString strmsg=ui->lineEdit_InputMsg->text();
    ui->plainTextEdit_DispMsg->appendPlainText("[out]:"+strmsg);
    ui->lineEdit_InputMsg->clear();

    QByteArray str=strmsg.toUtf8();
    str.append('\n');
    tcpclient->write(str);

}


void MainWindow::on_pushButton_Disconnect_clicked()
{
    if(tcpclient->state()==QAbstractSocket::ConnectedState)
        tcpclient->disconnectFromHost();
}




QString MainWindow::getlocalip() // 获取本机IP地址
{
    QString hostname=QHostInfo::localHostName();
    QHostInfo hostinfo=QHostInfo::fromName(hostname);

    QString localip="";

    QList<QHostAddress> addlist=hostinfo.addresses();
    if(!addlist.isEmpty())
    {
        for (int i=0;i<addlist.count();i++)
        {
            QHostAddress ahost=addlist.at(i);
            if(QAbstractSocket::IPv4Protocol==ahost.protocol())
            {
                localip=ahost.toString();
                break;
            }
        }
    }

    return localip;
}


void MainWindow::closeEvent(QCloseEvent *event)
{
    if(tcpclient->state()==QAbstractSocket::ConnectedState)
    {
        tcpclient->disconnectFromHost();
    }
    event->accept();

}


void MainWindow::connectfunc()
{
    ui->plainTextEdit_DispMsg->appendPlainText("**********已经连接到服务器端**********");
    ui->plainTextEdit_DispMsg->appendPlainText("**********peer address:"+
                                               tcpclient->peerAddress().toString());
    ui->plainTextEdit_DispMsg->appendPlainText("**********peer port:"+
                                               QString::number(tcpclient->peerPort()));

    ui->pushButton_Connect->setEnabled(false);
    ui->pushButton_Disconnect->setEnabled(true);

}
void MainWindow::disconnectfunc()
{
    ui->plainTextEdit_DispMsg->appendPlainText("**********已断开与服务器端的连接**********");

    ui->pushButton_Connect->setEnabled(true);
    ui->pushButton_Disconnect->setEnabled(false);

}
void MainWindow::socketreaddata()
{
    while(tcpclient->canReadLine())
        ui->plainTextEdit_DispMsg->appendPlainText("[in]:"+tcpclient->readLine());

}

上位机通过网络编程与下位机实现通信

Qt作为上位机

51、32单片机或ARM开发板开作为下位机

通过网络编程实现通信

上位机可作为服务端或客户端,下位机也可作为服务端或客户端,具体按各自的项目需求实现

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

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

相关文章

蓝桥杯-动态规划-子数组问题

目录 一、乘积最大数组 二、乘积为正数的最长子数组长度 三、等差数列划分 四、最长湍流子数组 心得&#xff1a; 最重要的还是状态表示&#xff0c;我们需要根据题的意思&#xff0c;来分析出不同的题&#xff0c;不同的情况&#xff0c;来分析需要多少个状态 一、乘积最…

Node.js与npm的准备与操作

1.下载 Node.js官网&#xff1a;Node.jsNode.js is a JavaScript runtime built on Chromes V8 JavaScript engine.https://nodejs.org/en 打开后的界面如下&#xff1a; LTS&#xff08;Long Term Support&#xff09;&#xff1a;长期支持版&#xff0c;稳定版 Current&am…

Vue+ElementUI+C#技巧分享:周数选择器

文章目录 前言一、周数的计算逻辑1.1 周数的定义1.2 年初周数的确定1.3 周数的计算方法 二、VueElementUI代码实现2.1 计算周数2.2 获取周的日期范围2.3 根据周数获取日期范围2.4 控件引用2.4.1 控件引用代码分析2.4.2 初始化变量代码分析 2.5 周数选择器完整代码 三、C#后端代…

10_7iic整体框架流程

在内核中 这边把iic整个流程分成了 4层 iic_dtiver at24_iic_eeprom 也就是我们的自己的驱动 i2c-core.c 核心层 i2c/busses/i2c-s3c2410.c 控制器层 平台总线驱动层,或者也是图中的设备树 硬件描述 我们假设 板子上有三个iic控制器 0 1 2 这里在控制器0 上挂载了gt24c02的eep…

Retrofit怎么返回一个JSON字符串?

项目用已经使用了 Retrofit&#xff0c;定义了接口方法&#xff0c;返回了 JSON 转换后的实体对象&#xff0c;炒鸡方便。但是总有意料之外的时候&#xff0c;比如我不需要返回实体对象&#xff0c;我要返回纯纯的 JSON 字符串&#xff0c;怎么办呢&#xff1f; 先看源码 通过…

ros2智能小车中STM32地盘需要用到PWM的模块

我做的地盘比较简单&#xff0c;使用了一下模块&#xff1a; 4个直流减速电机&#xff0c;&#xff08;每个模块用到了一个PWM&#xff09; 光电对射测速模块&#xff08;不用PWM) 超声波测距模块&#xff08;不用PWM&#xff0c;只需要测量时间&#xff09; sg90转向模块&…

C语言进阶-文件操作

目录 文件分类 程序文件 数据文件 文件的打开和关闭 文件指针 文件的顺序读写 文件读取结束的判定 文件缓冲区 文件版通讯录 实现代码 注意事项 ​编辑 ​编辑 实现效果 文件分类 磁盘上的文件是文件。 但是在程序设计中&#xff0c;我们一般谈的文件有两种&#xff1a;程…

【虚拟机】在VM中安装 CentOS 7

1.2.创建虚拟机 Centos7是比较常用的一个Linux发行版本&#xff0c;在国内的使用比例还是比较高的。 大家首先要下载一个Centos7的iso文件&#xff0c;我在资料中给大家准备了一个mini的版本&#xff0c;体积不到1G&#xff0c;推荐大家使用&#xff1a; 我们在VMware《主页》…

深入理解对象与垃圾回收机制

1、虚拟机中对象创建过程 1.1 对象创建过程 当我们使用 new 创建一个对象时&#xff0c;在 JVM 中进行了如下操作&#xff1a; 类加载&#xff1a;把 class 加载到 JVM 运行时数据区的过程。可以通过本地文件的形式&#xff0c;也可以通过网络加载。 检查加载&#xff1a;首…

【RTP】3: RTPSenderVideo::SendVideo 切片到发送

m98 版本。之前1 2 都是m79.RTPSenderVideo::SendVideo 负责切片,是入口 实际发送要靠: RTPSender* const rtp_sender_; 外部传递的: rtp_rtcp\source\rtp_sender.h 实现了rtp rtcp协议 ,负责实际的打包 新增了一个 TransformableFrameInterface 用的 编码线程 - RTPSend…

【数据库】缓冲区管理器结构,几种常用替换策略分析,pin钉住缓冲区块防止错误的替换,以及缓冲区管理带来的代价优化

缓冲区管理 ​专栏内容&#xff1a; 手写数据库toadb 本专栏主要介绍如何从零开发&#xff0c;开发的步骤&#xff0c;以及开发过程中的涉及的原理&#xff0c;遇到的问题等&#xff0c;让大家能跟上并且可以一起开发&#xff0c;让每个需要的人成为参与者。 本专栏会定期更新&…

【Qt】判断QList链表内是否有重复数据

QList<int> listInt;listInt.push_back(1);listInt.push_back(1);listInt.push_back(2);listInt.push_back(3);qDebug().noquote() << listInt.toSet().toList();

(数据结构)顺序表的定义

#include<stdio.h> //顺序表的实现——静态分配 #define MAX 10 //定义最大长度 typedef struct List {int data[MAX]; //用静态的数组存放数据int lenth; //顺序表现在的长度 }List; //顺序表的初始化 void ChuShiHua(List L) {L.lenth 0; //将顺序表的长度初始化…

MFC居中显示文字及其应用

首先获取窗口客户区矩形,然后使用DrawText输出,设置DT_CENTER 和 DT_VCENTER标志; 输出如上图;没有实现垂直居中; 最终的代码如下; void CcenterView::OnDraw(CDC* pDC) {CcenterDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);if (!pDoc)return;// TODO: 在此处为…

基于python协同过滤推荐算法的电影推荐与管理系统

欢迎大家点赞、收藏、关注、评论啦 &#xff0c;由于篇幅有限&#xff0c;只展示了部分核心代码。 文章目录 一项目简介 二、功能三、系统四. 总结 一项目简介 电影推荐与管理系统是一个基于Python的协同过滤推荐算法的应用&#xff0c;它可以帮助用户根据他们的兴趣和偏好进行…

一般将来时

一般将来时 概念 表示将要发生的动作或打算、计划准备做某事 时间 tomorrow 明天 the day after tomorrow 后天 next week 下周 next weekend 下周末 next month 下个月 next year 明年 ...句子结构 主语 be&#xff08;am/is/are&#xff09;going to do … 计划,…

手把手教会你--Hack The Box的账号注册(HTB Labs部分)

有什么问题&#xff0c;请尽情问博主&#xff0c;QQ群796141573 前言1.1 一次注册正确的注册过程1.2 讲讲我在注册过程中遇到的两个问题&#xff08;1&#xff09;点击REGISTER后无反应&#xff08;2&#xff09;提示Error! reCaptcha validation failed 前言 请务必跟着博主复…

GPT4测试 — 答题能力及文档处理能力

创建gdp.txt文件&#xff08;使用word 2013创建的文档测试了也可以&#xff0c;WPS建的不行&#xff09; 上传文件&#xff0c;输入prompt: 请帮我答题&#xff0c;把那个正确答案的选项的字母序号填在&#xff08;&#xff09;中&#xff0c;并返回文件blabla… 给我一个文件…

人工智能-优化算法和深度学习

优化和深度学习 对于深度学习问题&#xff0c;我们通常会先定义损失函数。一旦我们有了损失函数&#xff0c;我们就可以使用优化算法来尝试最小化损失。在优化中&#xff0c;损失函数通常被称为优化问题的目标函数。按照传统惯例&#xff0c;大多数优化算法都关注的是最小化。…

springboot核心原理之@SpringbootApplication

1.SpringbootApplication Configuration标志的类 在spring ioc启动的时候就会加载创建这个类对象 EnableAutoConfiguration 中有两个注解 &#xff08;1&#xff09;AutoConfigurationPackage 扫描主程序包(主程序main所在包及其子包) 可以看到这个类 &#xff1a; static c…