首页 > 编程语言 >05_QT网络编程之TCP通信

05_QT网络编程之TCP通信

时间:2024-04-13 23:24:09浏览次数:20  
标签:Widget tcpSocket QT 05 void widget TCP ui

QT网络编程之TCP通信

QT的网络编程:

​ 网络编程有TCP和UDP。

TCP编程需要用到俩个类:QTcpServer和QTcpSocket

本节课目标:

​ 完成一个TCP服务器和一个客户端。

TcpServer

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>510</width>
    <height>480</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="0" column="0">
    <layout class="QVBoxLayout" name="verticalLayout">
     <item>
      <widget class="QGroupBox" name="groupBox">
       <property name="title">
        <string>接收窗口</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QPlainTextEdit" name="receiveEdit">
       <property name="readOnly">
        <bool>true</bool>
       </property>
      </widget>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout_2">
       <item>
        <widget class="QLabel" name="label">
         <property name="text">
          <string>端口号:</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QLineEdit" name="portEdit"/>
       </item>
       <item>
        <spacer name="horizontalSpacer_3">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
      </layout>
     </item>
     <item>
      <widget class="QGroupBox" name="groupBox_2">
       <property name="title">
        <string>发送窗口</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QLineEdit" name="sendEdit"/>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <item>
        <widget class="QPushButton" name="openBt">
         <property name="text">
          <string>打开服务器</string>
         </property>
        </widget>
       </item>
       <item>
        <spacer name="horizontalSpacer">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="closeBt">
         <property name="text">
          <string>关闭服务器</string>
         </property>
        </widget>
       </item>
       <item>
        <spacer name="horizontalSpacer_2">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="sendBt">
         <property name="text">
          <string>发送数据</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

TcpServer.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-04-13T15:38:03
#
#-------------------------------------------------

QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = TcpServer
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has 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.0


SOURCES += \
        main.cpp \
        widget.cpp

HEADERS += \
        widget.h

FORMS += \
        widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    QTcpServer *tcpServer;
    QTcpSocket *tcpSocket;

private slots:
    void on_openBt_clicked();

    void on_closeBt_clicked();

    void on_sendBt_clicked();

    void newConnection_slot();
    void readyRead_slot();

private:
    Ui::Widget *ui;


};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

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

    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);


    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_slot()));
}


void Widget::newConnection_slot()
{
     tcpSocket = tcpServer->nextPendingConnection();
     connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));


}

void Widget:: readyRead_slot()
{
    QString buf;

    buf = tcpSocket->readAll();

    ui->receiveEdit->appendPlainText(buf);

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

void Widget::on_openBt_clicked()
{
   tcpServer->listen(QHostAddress::Any,ui->portEdit->text().toUInt());
}

void Widget::on_closeBt_clicked()
{
    tcpServer->close();
}

void Widget::on_sendBt_clicked()
{
    tcpSocket->write(ui->sendEdit->text().toLocal8Bit().data());
}

TcpClient

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>484</width>
    <height>496</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="0" column="0">
    <layout class="QVBoxLayout" name="verticalLayout">
     <item>
      <widget class="QGroupBox" name="groupBox">
       <property name="title">
        <string>接收框</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QPlainTextEdit" name="receiveEdit">
       <property name="readOnly">
        <bool>true</bool>
       </property>
      </widget>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout_2">
       <item>
        <widget class="QLabel" name="label">
         <property name="text">
          <string>端口号:</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QLineEdit" name="portEdit"/>
       </item>
       <item>
        <widget class="QLabel" name="label_2">
         <property name="text">
          <string>ip:</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QLineEdit" name="ipEdit"/>
       </item>
      </layout>
     </item>
     <item>
      <widget class="QGroupBox" name="groupBox_2">
       <property name="title">
        <string>发送框</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QLineEdit" name="sendEdit"/>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <item>
        <widget class="QPushButton" name="openBt">
         <property name="text">
          <string>打开客户端</string>
         </property>
        </widget>
       </item>
       <item>
        <spacer name="horizontalSpacer">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="closeBt">
         <property name="text">
          <string>关闭客户端</string>
         </property>
        </widget>
       </item>
       <item>
        <spacer name="horizontalSpacer_2">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>40</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="pushButton_3">
         <property name="text">
          <string>发送数据</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

TcpClient.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-04-13T16:10:28
#
#-------------------------------------------------

QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = TcpClient
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has 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.0


SOURCES += \
        main.cpp \
        widget.cpp

HEADERS += \
        widget.h

FORMS += \
        widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpSocket>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    QTcpSocket *tcpSocket;

private slots:
    void on_openBt_clicked();

    void on_closeBt_clicked();

    void on_pushButton_3_clicked();

    void connected_slot();
    void readyRead_slot();

private:
    Ui::Widget *ui;


};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

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

    tcpSocket = new QTcpSocket(this);
}

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

void Widget::on_openBt_clicked()
{
    tcpSocket->connectToHost(ui->ipEdit->text(), ui->portEdit->text().toUInt());
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected_slot()));
}

void Widget::connected_slot()
{
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readyRead_slot()));
}

void Widget::readyRead_slot()
{
    ui->receiveEdit->appendPlainText(tcpSocket->readAll());
}

void Widget::on_closeBt_clicked()
{
    tcpSocket->close();
}

void Widget::on_pushButton_3_clicked()
{
    tcpSocket->write(ui->sendEdit->text().toLocal8Bit().data());
}

标签:Widget,tcpSocket,QT,05,void,widget,TCP,ui
From: https://www.cnblogs.com/mzx233/p/18133577

相关文章

  • 04_把QT程序打包成Windows软件
    把QT程序打包成Windows软件问题一:什么是打包和部署?​因为我们要把写好的程序发给用户来用,我们写好的源码也不是随便给别人的。问题二:怎么打包和部署?1.我们把工厂切换到release模式,然后编译。​release模式:基本没有调试信息。​debug模式:有很多调试信息。......
  • 03_QT上位机开发之串口助手
    QT上位机开发之串口助手一.qt的三驾马车​ 1.qt下的串口编程​ 2.qt下的网络编程​ 3.qt下操作GPIO二.仿写串口助手MySerial.pro#-------------------------------------------------##ProjectcreatedbyQtCreator2024-04-12T18:07:26##--------------------------......
  • 02_QT信号和槽
    1.给控件改名字为了分析代码方便,我们要给控件改名字。要通俗易懂。2.什么是信号和槽信号:信号就是指控件发出的特定的信号。比如按钮的信号:![img](file:///C:/Users/机械革命/AppData/Local/Temp/msohtmlclip1/01/clip_image001.png)槽:槽就是槽函数的意思,我们可以把槽函数绑......
  • 4-WIFI&蓝牙(ESP32)转CAN或RS485总线&串口TTL模块-CSDK-设备作为TCP客户端,实现上位机
    <p><iframename="ifd"src="https://mnifdv.cn/resource/cnblogs/ESP32_CAN"frameborder="0"scrolling="auto"width="100%"height="1500"></iframe></p> 说明这节设备作为TCP客户端,连接上位......
  • Qt | 一文总结QObject
    Qt|一文总结QObject来源 https://zhuanlan.zhihu.com/p/608004472 一、QObject的重要知识QObject是Qt对象模型的核心。这个模型的核心特性是一个强大的无缝对象通信机制,即信号和槽。可以使用connect()将信号连接到槽函数,并使用disconnect()破坏已经存在的连接。为了避免永......
  • 3-WIFI&蓝牙(ESP32)转CAN或RS485总线&串口TTL模块-CSDK--设备作为TCP服务器,实现上位
    <p><iframename="ifd"src="https://mnifdv.cn/resource/cnblogs/ESP32_CAN"frameborder="0"scrolling="auto"width="100%"height="1500"></iframe></p> 说明这节设备作为TCP服务器,上位机T......
  • MySQL 8 显示错误代码2058
    在使用mysql-uroot-P3307-proot和SQLyong连接MySQL时报错1.在MySQL8.3CommandLineClient登录点击查看代码Enterpassword:****WelcometotheMySQLmonitor.Commandsendwith;or\g.YourMySQLconnectionidis14Serverversion:8.3.0MySQLCommunitySer......
  • 【Qt】编写的qt程序,如何把依赖的dll自动拷贝到exe同级目录
    如果你的Qt程序在VisualStudio中可以正常启动但直接启动exe文件会报错,可能是因为缺少依赖的QtDLL文件导致的。为了确定缺少了哪些DLL文件,你可以尝试以下方法:使用DependencyWalker:DependencyWalker是一个工具,可以帮助你分析可执行文件的依赖关系,并找出缺失的D......
  • 2.创建Qt项目
    2.创建Qt项目2.1使用向导创建打开QtCreator界面选择NewProject或者选择菜单栏【文件】-【新建文件或项目】菜单项弹出NewProject对话框,选择QtWidgetsApplication,选择【Choose】按钮,弹出如下对话框设置项目名称和路径,按照向导进行下一步,选择编译套件向导会默认......
  • ESP32 Arduino开发 MQTT
    ESP32Arduino开发MQTT目录ESP32Arduino开发MQTT1.安装程序库2.编写相关程序2.1.引入头文件2.2.定义MQTT相关参数2.3.创建对象2.4.连接网络2.5.连接MQTT服务器2.6.MQTT回调函数3.完整的代码例程4.MQTT连接测试1.安装程序库打开库管理工具工具->管理库.........