QT中基于TCP的网络通信

ops/2024/10/18 20:21:29/

QT中基于TCP的网络通信

  • QTcpServer
    • 公共成员函数
    • 信号
  • QTcpSocket
    • 公共成员函数
    • 信号
  • 通信流程
    • 服务器端
      • 通信流程
      • 代码
    • 客户端
      • 通信流程
      • 代码
  • 多线程网络通信
    • SendFileClient
    • SendFileServer

使用Qt提供的类进行基于TCP的套接字通信需要用到两个类:

QTcpServer:服务器类,用于监听客户端连接以及和客户端建立连接。
QTcpSocket:通信的套接字类,客户端、服务器端都需要使用。
这两个套接字通信类都属于网络模块network。

QTcpServer

QTcpServer类 用于监听客户端连接以及和客户端建立连接,在使用之前先介绍一下这个类提供的一些常用API函数

公共成员函数

构造函数

QTcpServer::QTcpServer(QObject *parent = Q_NULLPTR);

给监听的套接字设置监听

bool QTcpServer::listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
// 判断当前对象是否在监听, 是返回true,没有监听返回false
bool QTcpServer::isListening() const;
// 如果当前对象正在监听返回监听的服务器地址信息, 否则返回 QHostAddress::Null
QHostAddress QTcpServer::serverAddress() const;
// 如果服务器正在侦听连接,则返回服务器的端口; 否则返回0
quint16 QTcpServer::serverPort() const

参数:
address:通过类QHostAddress可以封装IPv4、IPv6格式的IP地址,QHostAddress::Any表示自动绑定
port:如果指定为0表示随机绑定一个可用端口。
返回值:绑定成功返回true,失败返回false

QTcpSocket *QTcpServer::nextPendingConnection();

得到和客户端建立连接之后用于通信的QTcpSocket套接字对象,它是QTcpServer的一个子对象,当QTcpServer对象析构的时候会自动析构这个子对象,当然也可自己手动析构,建议用完之后自己手动析构这个通信的QTcpSocket对象。

bool QTcpServer::waitForNewConnection(int msec = 0, bool *timedOut = Q_NULLPTR);

阻塞等待客户端发起的连接请求,不推荐在单线程程序中使用,建议使用非阻塞方式处理新连接,即使用信号 newConnection() 。

参数:
msec:指定阻塞的最大时长,单位为毫秒(ms)
timeout:传出参数,如果操作超时timeout为true,没有超时timeout为false

信号

当接受新连接导致错误时,将发射如下信号。socketError参数描述了发生的错误相关的信息。

[signal] void QTcpServer::acceptError(QAbstractSocket::SocketError socketError);

每次有新连接可用时都会发出 newConnection() 信号。

[signal] void QTcpServer::newConnection();

QTcpSocket

QTcpSocket是一个套接字通信类,不管是客户端还是服务器端都需要使用。在Qt中发送和接收数据也属于IO操作(网络IO),先来看一下这个类的继承关系:

在这里插入图片描述

公共成员函数

构造函数

QTcpSocket::QTcpSocket(QObject *parent = Q_NULLPTR);

连接服务器,需要指定服务器端绑定的IP和端口信息。

[virtual] void QAbstractSocket::connectToHost(const QString &hostName, quint16 port, OpenMode openMode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol);[virtual] void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port, OpenMode openMode = ReadWrite);

在Qt中不管调用读操作函数接收数据,还是调用写函数发送数据,操作的对象都是本地的由Qt框架维护的一块内存。因此,调用了发送函数数据不一定会马上被发送到网络中,调用了接收函数也不是直接从网络中接收数据,关于底层的相关操作是不需要使用者来维护的。

接收数据

// 指定可接收的最大字节数 maxSize 的数据到指针 data 指向的内存中
qint64 QIODevice::read(char *data, qint64 maxSize);
// 指定可接收的最大字节数 maxSize,返回接收的字符串
QByteArray QIODevice::read(qint64 maxSize);
// 将当前可用操作数据全部读出,通过返回值返回读出的字符串
QByteArray QIODevice::readAll();

发送数据

// 发送指针 data 指向的内存中的 maxSize 个字节的数据
qint64 QIODevice::write(const char *data, qint64 maxSize);
// 发送指针 data 指向的内存中的数据,字符串以 \0 作为结束标记
qint64 QIODevice::write(const char *data);
// 发送参数指定的字符串
qint64 QIODevice::write(const QByteArray &byteArray);

信号

在使用QTcpSocket进行套接字通信的过程中,如果该类对象发射出readyRead()信号,说明对端发送的数据达到了,之后就可以调用 read 函数接收数据了。

[signal] void QIODevice::readyRead();

调用connectToHost()函数并成功建立连接之后发出connected()信号。

[signal] void QAbstractSocket::connected();

在套接字断开连接时发出disconnected()信号。

[signal] void QAbstractSocket::disconnected();

通信流程

在这里插入图片描述

服务器端

通信流程

  1. 创建套接字服务器QTcpServer对象
  2. 通过QTcpServer对象设置监听,即:QTcpServer::listen()
  3. 基于QTcpServer::newConnection()信号检测是否有新的客户端连接
  4. 如果有新的客户端连接调用QTcpSocket
  5. *QTcpServer::nextPendingConnection()得到通信的套接字对象
  6. 使用通信的套接字对象QTcpSocket和客户端进行通信

代码

服务器端的窗口界面如下图所示:
在这里插入图片描述

QtServer.pro文件

在这里插入图片描述

mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>
#include <QLabel>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_setListen_clicked();void on_sendMsg_clicked();private:Ui::MainWindow *ui;QTcpServer* m_s;QTcpSocket* m_tcp;QLabel* m_status;
};
#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);ui->port->setText("8000"); //先设置一个端口号setWindowTitle("服务器");//创建监听的服务器对象m_s = new QTcpServer(this); //指定父对象,不需要再去管内存的释放//等待客户端链接,连接上会发送一个信号newConnectionconnect(m_s,&QTcpServer::newConnection,this,[=](){m_tcp = m_s->nextPendingConnection(); //得到可供通讯的套接字对象m_status->setPixmap(QPixmap(":/connect.png").scaled(20,20)); //更改链接状态//检测是否可以接收数据connect(m_tcp,&QTcpSocket::readyRead,this,[=](){QByteArray data = m_tcp->readAll(); //全部读出来ui->record->append("客户端say: " + data);  //显示在历史记录框中});//对端断开链接时会,TcpSocket会发送一个disconnect信号connect(m_tcp,&QTcpSocket::disconnected,this,[=](){m_tcp->close(); //关闭套接字m_tcp->deleteLater(); //释放m_tcpm_status->setPixmap(QPixmap(":/disconnect.png").scaled(20,20)); //更改链接状态});});//状态栏m_status = new QLabel;//给标签设置图片m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20,20));  //scaled设置图片大小//将标签设置到状态栏中ui->statusbar->addWidget(new QLabel("连接状态: "));ui->statusbar->addWidget(m_status);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_setListen_clicked()
{unsigned short port = ui->port->text().toUShort();m_s->listen(QHostAddress::Any,port); //开始监听ui->setListen->setDisabled(true);  //监听之后设置为不可用状态
}void MainWindow::on_sendMsg_clicked()
{QString msg = ui->msg->toPlainText(); //以纯文本的方式把数据读出来m_tcp->write(msg.toUtf8());ui->record->append("服务器say: " + msg);  //显示在历史记录框中
}

mainwindow.ui文件
在这里插入图片描述

客户端

通信流程

  1. 创建通信的套接字类QTcpSocket对象
  2. 使用服务器端绑定的IP和端口连接服务器QAbstractSocket::connectToHost()
  3. 使用QTcpSocket对象和服务器进行通信

代码

客户端的窗口界面如下图所示:
在这里插入图片描述

QtClient.pro文件
在这里插入图片描述
mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpSocket>
#include <QLabel>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_sendMsg_clicked();void on_connect_clicked();void on_disconnect_clicked();private:Ui::MainWindow *ui;QTcpSocket* m_tcp;QLabel* m_status;
};
#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 <QHostAddress>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);ui->port->setText("8000"); //先设置一个端口号ui->ip->setText("127.0.0.1"); //设置本地循环ipsetWindowTitle("客户端");ui->disconnect->setDisabled(true);//断开连接按钮不可用//创建监听的服务器对象m_tcp = new QTcpSocket(this); //指定父对象,不需要再去管内存的释放//检测是否可以接受数据 当 m_tcp 发送给出readyRead信号,就说明有信号到达了connect(m_tcp,&QTcpSocket::readyRead,this,[=](){QByteArray data = m_tcp->readAll(); //全部读出来ui->record->append("服务器say: " + data);  //显示在历史记录框中});//对端断开链接时会,TcpSocket会发送一个disconnect信号connect(m_tcp,&QTcpSocket::disconnected,this,[=](){m_tcp->close(); //关闭套接字//m_tcp->deleteLater(); // 指定了父对象,不需要手动释放 m_tcpm_status->setPixmap(QPixmap(":/disconnect.png").scaled(20,20)); //更改链接状态ui->record->append("服务器已经和客户端断开了连接...");ui->connect->setDisabled(false); //连接按钮可用ui->disconnect->setEnabled(false); //断开连接按钮不可用});//当 m_tcp 发送一个 connected 信号后,就说明已经连接上服务器connect(m_tcp,&QTcpSocket::connected,this,[=](){m_status->setPixmap(QPixmap(":/connect.png").scaled(20,20));  //scaled设置图片大小ui->record->append("已经成功连接到了服务器...");ui->connect->setDisabled(true); //连接按钮不可用ui->disconnect->setEnabled(true); //断开连接按钮可用});//状态栏m_status = new QLabel;//给标签设置图片m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20,20));  //scaled设置图片大小//将标签设置到状态栏中ui->statusbar->addWidget(new QLabel("连接状态: "));ui->statusbar->addWidget(m_status);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_sendMsg_clicked()
{QString msg = ui->msg->toPlainText(); //以纯文本的方式把数据读出来m_tcp->write(msg.toUtf8());ui->record->append("客户端say: " + msg);  //显示在历史记录框中
}void MainWindow::on_connect_clicked()
{QString ip = ui->ip->text();unsigned short port = ui->port->text().toUShort();m_tcp->connectToHost(QHostAddress(ip),port);
}void MainWindow::on_disconnect_clicked()
{m_tcp->close();ui->connect->setDisabled(false);ui->disconnect->setEnabled(false);
}

mainwindow.ui文件
在这里插入图片描述

多线程网络通信

客户端通过子线程发送文件,服务器通过子线程接收文件。

通信界面
在这里插入图片描述

SendFileClient

在这里插入图片描述
mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();signals:
void startConnect(unsigned short,QString ip);
void sendFile(QString path);private slots:void on_connectServer_clicked();void on_selFile_clicked();void on_sendFile_clicked();private:Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

sendfile.h文件

#ifndef SENDFILE_H
#define SENDFILE_H#include <QObject>
#include <QTcpSocket>class SendFile : public QObject
{Q_OBJECT
public:explicit SendFile(QObject *parent = nullptr);//连接服务器void connectServer(unsigned short port,QString ip);//发送文件void sendFile(QString path);signals:void connectOk();void gameOver();void CurPercent(int num);
private:QTcpSocket* m_tcp;};#endif // SENDFILE_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>
#include <QThread>
#include "sendfile.h"
#include <QFileDialog>
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);setFixedSize(400,300);setWindowTitle("客户端");qDebug() << "主线程: " << QThread::currentThread();ui->ip->setText("127.0.0.1");ui->port->setText("8000");ui->progressBar->setRange(0,100); //进度条设置范围ui->progressBar->setValue(0); //进度设置初始值//创建线程对象QThread* t = new QThread;//创建任务对象SendFile* worker = new SendFile;worker->moveToThread(t);  //worker对象就会在 线程 t 里面执行connect(this,&MainWindow::sendFile,worker,&SendFile::sendFile);connect(this,&MainWindow::startConnect,worker,&SendFile::connectServer);//处理子线程发送的信号connect(worker,&SendFile::connectOk,this,[=](){QMessageBox::information(this,"连接服务器","已经成功连接了服务器");});connect(worker,&SendFile::gameOver,this,[=](){//资源释放t->quit();t->wait();worker->deleteLater();t->deleteLater();});//接受子线程发送的数据,更新进度条connect(worker,&SendFile::CurPercent,ui->progressBar,&QProgressBar::setValue);t->start(); //启动线程}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_connectServer_clicked()
{QString ip = ui->ip->text(); //获取ipunsigned short port = ui->port->text().toUShort();emit startConnect(port,ip); //发送连接信号
}void MainWindow::on_selFile_clicked()
{QString path = QFileDialog::getOpenFileName(); //获取文件路径if(path.isEmpty()){QMessageBox::warning(this,"打开文件","选择的文件路径不能为空!");return;}ui->filePath->setText(path);
}void MainWindow::on_sendFile_clicked()
{emit sendFile(ui->filePath->text());
}

sendfile.cpp文件

#include "sendfile.h"#include <QFile>
#include <QFileInfo>
#include <QHostAddress>
#include <QDebug>
#include <QThread>SendFile::SendFile(QObject *parent) : QObject(parent)
{}void SendFile::connectServer(unsigned short port, QString ip)
{qDebug() << "连接服务器线程: " << QThread::currentThread();m_tcp = new QTcpSocket;m_tcp->connectToHost(QHostAddress(ip),port);//当m_tcp发送connected信号后,表示已经连接成功了connect(m_tcp,&QTcpSocket::connected,this,&SendFile::connectOk);//当m_tcp发送disconnected信号后,表示服务器断开连接了connect(m_tcp,&QTcpSocket::disconnected,this,[=](){m_tcp->close();m_tcp->deleteLater();//发送信号给主线程,告诉主线程服务器已经断开连接emit gameOver();});
}void SendFile::sendFile(QString path)
{qDebug() << "发送文件线程: " << QThread::currentThread();QFile file(path);QFileInfo info(path);int fileSize = info.size(); //求文件大小file.open(QFile::ReadOnly); //只读形式while(!file.atEnd()){//第一次循环的时候,要把文件大小传送过去static int num = 0;if(num==0){m_tcp->write((char*)&fileSize, 4);}QByteArray line = file.readLine(); //一行一行读num += line.size();int percent = (num*100 / fileSize);emit CurPercent(percent); //更新传送文件的百分比m_tcp->write(line); //将数据发送给服务器}
}

SendFileServer

在这里插入图片描述
mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpServer>
#include "mytcpserver.h"QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_setListen_clicked();private:Ui::MainWindow *ui;MyTcpServer* m_s;
};
#endif // MAINWINDOW_H

mytcpserver.h文件

#ifndef MYTCPSERVER_H
#define MYTCPSERVER_H#include <QTcpServer>class MyTcpServer : public QTcpServer
{Q_OBJECT
public:explicit MyTcpServer(QObject *parent = nullptr);protected:virtual void incomingConnection(qintptr socketDescriptor) override;
signals:void newDescriptor(qintptr sock);};#endif // MYTCPSERVER_H

recvfile.h文件

#ifndef RECVFILE_H
#define RECVFILE_H#include <QThread>
#include <QTcpSocket>class RecvFile : public QThread
{Q_OBJECT
public:explicit RecvFile(qintptr sock,QObject *parent = nullptr);protected:void run() override;
private:QTcpSocket* m_tcp;
signals:void over();
};#endif // RECVFILE_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>
#include <QTcpSocket>
#include "recvfile.h"
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);setFixedSize(400,300);setWindowTitle("服务器");qDebug()<<"服务器主线程: "<<QThread::currentThread();m_s = new MyTcpServer(this);//检测是否有连接信号connect(m_s,&MyTcpServer::newDescriptor,this,[=](qintptr sock){// QTcpSocket* tcp = m_s->nextPendingConnection(); //得到用于通讯的Socket对象//创建子线程RecvFile* subThread  =new RecvFile(sock);subThread->start(); //启动子线程//接收子线程信号connect(subThread,&RecvFile::over,this,[=](){subThread->exit();subThread->wait();subThread->deleteLater();QMessageBox::information(this,"文件接收","文件接收完毕!!!");});});}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_setListen_clicked()
{unsigned short port = ui->port->text().toUShort();m_s->listen(QHostAddress::Any,port);
}

mytcpserver.cpp文件

#include "mytcpserver.h"MyTcpServer::MyTcpServer(QObject *parent) : QTcpServer(parent)
{}//当客户端发起新的连接,就会被自动调用
void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{//不能在子线程里面直接使用主线程定义的套接字对象,自己在子线程中定义一个emit newDescriptor(socketDescriptor);
}

recvfile.cpp文件

#include "recvfile.h"
#include <QFile>
#include <QDebug>RecvFile::RecvFile(qintptr sock,QObject *parent) : QThread(parent)
{m_tcp = new QTcpSocket(this);m_tcp->setSocketDescriptor(sock);
}void RecvFile::run()
{qDebug() << "服务器子线程: " << QThread::currentThread();QFile* file = new QFile("recv.txt");file->open(QFile::WriteOnly);//接受数据connect(m_tcp,&QTcpSocket::readyRead,this,[=](){static int count = 0;static int total = 0;if(count ==0) //第一次接收,把文件大小接收过来{m_tcp->read((char*)&total,4); //接收4个字节}//读剩余的数据QByteArray all = m_tcp->readAll();count += all.size();file->write(all);//判断数据是否接收完毕if(count==total){m_tcp->close();m_tcp->deleteLater();file->close();file->deleteLater();//发送信号告诉子线程数据已经接收完emit over();}});//进入事件循环exec(); //保证子线程不退出
}

http://www.ppmy.cn/ops/26513.html

相关文章

洗鞋店上门预约小程序

洗鞋上门预约小程序&#xff0c;一款针对洗鞋行业的移动应用&#xff0c;让你轻松享受洗鞋的便捷服务。只需一键预约&#xff0c;多种洗鞋选项任你选&#xff0c;满足你的个性化需求。简洁明了的操作界面&#xff0c;让你快速下单&#xff0c;享受高效的洗鞋体验。 该系统凭借…

SpringBoot对接口配置跨域设置

目录 1. 使用 CrossOrigin 注解 2. 全局跨域配置 2.1. 注意事项 在 Spring Boot 应用中&#xff0c;接口配置跨域&#xff08;Cross-Origin Resource Sharing&#xff0c;CORS&#xff09;设置是一个常见的需求&#xff0c;特别是当你的前端应用和后端服务部署在不同的域名下…

牛客NC98 判断t1树中是否有与t2树完全相同的子树【simple 深度优先dfs C++/Java/Go/PHP】

题目 题目链接&#xff1a; https://www.nowcoder.com/practice/4eaccec5ee8f4fe8a4309463b807a542 思路 深度优先搜索暴力匹配 思路和算法这是一种最朴素的方法——深度优先搜索枚举 s 中的每一个节点&#xff0c;判断这个点的子树是否和 t 相等。如何判断一个节点的子树是否…

利用大型语言模型提升个性化推荐的异构知识融合方法

在推荐系统中&#xff0c;分析和挖掘用户行为是至关重要的&#xff0c;尤其是在美团外卖这样的平台上&#xff0c;用户行为表现出多样性&#xff0c;包括不同的行为主体&#xff08;如商家和产品&#xff09;、内容&#xff08;如曝光、点击和订单&#xff09;和场景&#xff0…

24.什么是跨域?解决方案有哪些?

为什么会出现跨域问题 存在浏览器同源策略&#xff0c;所以才会有跨域问题。那么浏览器是出于何种原因会有跨域的限制呢。其实不难想到&#xff0c;跨域限制主要的目的就是为了用户的上网安全。 同源策略导致的跨域是浏览器单方面拒绝响应数据&#xff0c;服务器端是处理完毕…

Docker基本命令

以下是一些常用的Docker基本命令&#xff1a; docker run&#xff1a;启动一个容器 示例&#xff1a;docker run hello-world docker ps&#xff1a;列出所有正在运行的容器 示例&#xff1a;docker ps docker images&#xff1a;列出所有本地镜像 示例&#xff1a;docker im…

[论文阅读] 测试时间自适应TTA

最初接触 CVPR2024 TEA: Test-time Energy Adaptation [B站]&#xff08;1:35:00-1:53:00&#xff09;https://www.bilibili.com/video/BV1wx4y1v7Jb/?spm_id_from333.788&vd_source145b0308ef7fee4449f12e1adb7b9de2 实现&#xff1a; 读取预训练好的模型参数设计需要更…

Github创建远程仓库(项目)

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…