十四、Qt主机信息与网络编程

一、主机信息

1、主机信息接口

  • QHostInfo:获取主机名称和IP地址
  • QNetWorkInterface:获取主机的所有网络接口,包括子网掩码和广播地址等

(1)使用

项目添加模块
QT       += network

2、实现程序

在这里插入图片描述

(1)创建项目,基于QDialog

在这里插入图片描述

(2)实现功能

#ifndef DIALOG_H
#define DIALOG_H#include <QDialog>#include <QHostInfo>
#include <QNetworkInterface>namespace Ui
{
class Dialog;
}class Dialog : public QDialog
{Q_OBJECTprivate:QString protocolName(QAbstractSocket::NetworkLayerProtocol protocol);public:explicit Dialog(QWidget *parent = nullptr);~Dialog();private slots:void on_btnHostIP_clicked();void on_btnClearText_clicked();void on_btnDnsIP_clicked();void on_lookUpHostInfo(QHostInfo host);void on_btnAllAddresses_clicked();void on_btnAllInterface_clicked();private:Ui::Dialog *ui;
};#endif // DIALOG_H
#include "dialog.h"
#include "ui_dialog.h"QString Dialog::protocolName(QAbstractSocket::NetworkLayerProtocol protocol)
{switch (protocol){case QAbstractSocket::IPv4Protocol:return "IPv4 Protocol";break;case QAbstractSocket::IPv6Protocol:return "IPv6 Protocol";break;case QAbstractSocket::AnyIPProtocol:return "AnyIP Protocol";break;default:return "Unknown Protocol";break;}
}Dialog::Dialog(QWidget *parent) :QDialog(parent),ui(new Ui::Dialog)
{ui->setupUi(this);
}Dialog::~Dialog()
{delete ui;
}void Dialog::on_btnHostIP_clicked()
{QString hostName = QHostInfo::localHostName();ui->plainTextEdit->appendPlainText(hostName);QHostInfo hostInfo = QHostInfo::fromName(hostName);QList<QHostAddress> addList = hostInfo.addresses();foreach (auto aHost, addList){if(ui->checkBox->isChecked()){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){ui->plainTextEdit->appendPlainText("协议:" + protocolName(aHost.protocol()));ui->plainTextEdit->appendPlainText("本机IP地址:" + aHost.toString());ui->plainTextEdit->appendPlainText("");}}else{ui->plainTextEdit->appendPlainText("协议:" + protocolName(aHost.protocol()));ui->plainTextEdit->appendPlainText("本机IP地址:" + aHost.toString());ui->plainTextEdit->appendPlainText("");}}
}void Dialog::on_btnClearText_clicked()
{ui->plainTextEdit->clear();
}void Dialog::on_btnDnsIP_clicked()
{// 异步方式QString hostName = ui->lineEdit->text();ui->plainTextEdit->appendPlainText("正在查询主机信息:" + hostName);QHostInfo::lookupHost(hostName, this, SLOT(on_lookUpHostInfo(QHostInfo)));
}void Dialog::on_lookUpHostInfo(QHostInfo host)
{QList<QHostAddress> addList = host.addresses();foreach (auto aHost, addList){if(ui->checkBox->isChecked()){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){ui->plainTextEdit->appendPlainText("协议:" + protocolName(aHost.protocol()));ui->plainTextEdit->appendPlainText("IP地址:" + aHost.toString());ui->plainTextEdit->appendPlainText("");}}else{ui->plainTextEdit->appendPlainText("协议:" + protocolName(aHost.protocol()));ui->plainTextEdit->appendPlainText("IP地址:" + aHost.toString());ui->plainTextEdit->appendPlainText("");}}
}void Dialog::on_btnAllAddresses_clicked()
{QList<QHostAddress> addList = QNetworkInterface::allAddresses();foreach (auto aHost, addList){if(ui->checkBox->isChecked()){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){ui->plainTextEdit->appendPlainText("协议:" + protocolName(aHost.protocol()));ui->plainTextEdit->appendPlainText("IP地址:" + aHost.toString());ui->plainTextEdit->appendPlainText("");}}else{ui->plainTextEdit->appendPlainText("协议:" + protocolName(aHost.protocol()));ui->plainTextEdit->appendPlainText("IP地址:" + aHost.toString());ui->plainTextEdit->appendPlainText("");}}
}void Dialog::on_btnAllInterface_clicked()
{QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();foreach (auto aInterface, list){if(!aInterface.isValid()){continue;}ui->plainTextEdit->appendPlainText("设备名称: " + aInterface.humanReadableName());ui->plainTextEdit->appendPlainText("硬件地址: " + aInterface.hardwareAddress());QList<QNetworkAddressEntry> entryList = aInterface.addressEntries();foreach (auto aEntry, entryList){ui->plainTextEdit->appendPlainText("  IP地址: " + aEntry.ip().toString());ui->plainTextEdit->appendPlainText("  子网掩码: " + aEntry.netmask().toString());ui->plainTextEdit->appendPlainText("  广播地址: " + aEntry.broadcast().toString());}ui->plainTextEdit->appendPlainText("");}
}

在这里插入图片描述

二、TCP通信

TCP是一种被大多数Internet网络协议(HTTP、FTP等)用于数据传输的低级网络协议,是可靠的、面向流、面向连接的传输协议。

1、相关类

(1)继承关系

QIODeviceQAbstractSocketQTcpSocketQSctpSocketQSslSocket // 加密QUdpSocket			

2、实现服务端程序

在这里插入图片描述

(1)创建项目

(2)添加图标资源

在这里插入图片描述

(3)实现服务器功能

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpSocket>
#include <QTcpServer>
#include <QLabel>namespace Ui
{
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTprivate:QLabel *labListen;QLabel *labSocketState;QTcpServer *tcpServer;QTcpSocket *tcpSocket;public:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();protected:void closeEvent(QCloseEvent *event);private:QString getLocalIP();private slots:void on_newConnection();void on_clientConnected();void on_clientDisconnected();void on_clientStateChanged(QAbstractSocket::SocketState state);void on_clientReadyRead();void on_actStartListen_triggered();void on_actStopListen_triggered();void on_actClearText_triggered();void on_btnSend_clicked();private:Ui::MainWindow *ui;
};#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"#include <QHostInfo>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);labListen = new QLabel("监听状态:");labListen->setMinimumWidth(200);labSocketState = new QLabel("Socket状态:");labSocketState->setMinimumWidth(200);ui->statusBar->addWidget(labListen);ui->statusBar->addWidget(labSocketState);setWindowTitle("服务器:" + getLocalIP());tcpServer = new QTcpServer(this);connect(tcpServer, SIGNAL(newConnection()),this, SLOT(on_newConnection()));}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::closeEvent(QCloseEvent *event)
{if(tcpServer->isListening()){tcpServer->close();}event->accept();
}QString MainWindow::getLocalIP()
{QString hostName = QHostInfo::localHostName();QHostInfo hostInfo = QHostInfo::fromName(hostName);QString loaclIP;QList<QHostAddress> addList = hostInfo.addresses();foreach (auto aHost, addList){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){if(loaclIP.isEmpty()){loaclIP = aHost.toString();}ui->comboBoxAddresses->addItem(aHost.toString());}}return loaclIP;
}void MainWindow::on_newConnection()
{tcpSocket = tcpServer->nextPendingConnection(); //获取socketconnect(tcpSocket, SIGNAL(connected()), this, SLOT(on_clientConnected()));on_clientConnected(); //当前状态已经发送,需要直接调用通知connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(on_clientDisconnected()));connect(tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),this, SLOT(on_clientStateChanged(QAbstractSocket::SocketState)));on_clientStateChanged(tcpSocket->state()); //当前状态已经发送,需要直接调用通知connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(on_clientReadyRead()));}void MainWindow::on_clientConnected()
{ui->plainTextEdit->appendPlainText("**client socket connected");ui->plainTextEdit->appendPlainText("**peer address: " + tcpSocket->peerAddress().toString());ui->plainTextEdit->appendPlainText("**peer port " + QString::number(tcpSocket->peerPort()));
}void MainWindow::on_clientDisconnected()
{ui->plainTextEdit->appendPlainText("**client socket disconnected");tcpSocket->deleteLater();
}void MainWindow::on_clientStateChanged(QAbstractSocket::SocketState state)
{switch (state){case QAbstractSocket::UnconnectedState:labSocketState->setText("socket状态:UnconnectedState");break;case QAbstractSocket::HostLookupState:labSocketState->setText("socket状态:HostLookupState");break;case QAbstractSocket::ConnectingState:labSocketState->setText("socket状态:ConnectingState");break;case QAbstractSocket::ConnectedState:labSocketState->setText("socket状态:ConnectedState");break;case QAbstractSocket::BoundState:labSocketState->setText("socket状态:BoundState");break;case QAbstractSocket::ListeningState:labSocketState->setText("socket状态:ListeningState");break;case QAbstractSocket::ClosingState:labSocketState->setText("socket状态:ClosingState");break;default:break;}
}void MainWindow::on_clientReadyRead()
{//    while(tcpSocket->canReadLine())int nLen = 0;do{char data[1024] = {0};nLen = tcpSocket->readLine(data, 1023);if(nLen > 0){ui->plainTextEdit->appendPlainText(QString::asprintf("[in]: %s", data));}} while(nLen > 0);
}void MainWindow::on_actStartListen_triggered()
{QString IP = ui->comboBoxAddresses->currentText();int port = ui->spinBoxPort->value();QHostAddress addr(IP);tcpServer->listen(addr, port);ui->plainTextEdit->appendPlainText("**开始监听");ui->plainTextEdit->appendPlainText("**服务IP:" + tcpServer->serverAddress().toString());ui->plainTextEdit->appendPlainText("**服务器端口:" + QString::number(tcpServer->serverPort()));ui->actStartListen->setEnabled(false);ui->actStopListen->setEnabled(true);labListen->setText("监听状态:开始");
}void MainWindow::on_actStopListen_triggered()
{if(tcpServer->isListening()){tcpServer->close();ui->actStartListen->setEnabled(true);ui->actStopListen->setEnabled(false);labListen->setText("监听状态:停止");}
}void MainWindow::on_actClearText_triggered()
{ui->plainTextEdit->clear();
}void MainWindow::on_btnSend_clicked()
{QString msg = ui->lineEdit->text();ui->plainTextEdit->appendPlainText("[out] " + msg);ui->lineEdit->clear();ui->lineEdit->setFocus();msg += "\n";QByteArray data = msg.toUtf8();tcpSocket->write(data);
}

3、实现客户端程序

在这里插入图片描述

(1)创建项目

(2)添加图标资源

在这里插入图片描述

(3)实现功能

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QMainWindow>
#include <QTcpSocket>
#include <QLabel>namespace Ui
{
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTprivate:QLabel *labSocketState;QTcpSocket *tcpSocket;public:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();private:QString getLocalIP();private slots:void on_Connected();void on_Disconnected();void on_StateChanged(QAbstractSocket::SocketState state);void on_ReadyRead();void on_btnSend_clicked();void on_actConnect_triggered();void on_actDisconnect_triggered();void on_actClear_triggered();private:Ui::MainWindow *ui;
};#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"#include <QHostInfo>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);labSocketState = new QLabel("Socket状态:");labSocketState->setMinimumWidth(200);ui->statusBar->addWidget(labSocketState);setWindowTitle("客户端:" + getLocalIP());tcpSocket = new QTcpSocket;connect(tcpSocket, SIGNAL(connected()), this, SLOT(on_Connected()));connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(on_Disconnected()));connect(tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),this, SLOT(on_StateChanged(QAbstractSocket::SocketState)));connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(on_ReadyRead()));
}MainWindow::~MainWindow()
{delete ui;
}QString MainWindow::getLocalIP()
{QString hostName = QHostInfo::localHostName();QHostInfo hostInfo = QHostInfo::fromName(hostName);QString loaclIP;QList<QHostAddress> addList = hostInfo.addresses();foreach (auto aHost, addList){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){if(loaclIP.isEmpty()){loaclIP = aHost.toString();}ui->comboBox->addItem(aHost.toString());}}return loaclIP;
}void MainWindow::on_Connected()
{ui->plainTextEdit->appendPlainText("**socket connected");ui->plainTextEdit->appendPlainText("**peer address: " + tcpSocket->peerAddress().toString());ui->plainTextEdit->appendPlainText("**peer port " + QString::number(tcpSocket->peerPort()));
}void MainWindow::on_Disconnected()
{ui->plainTextEdit->appendPlainText("**socket disconnected");
}void MainWindow::on_StateChanged(QAbstractSocket::SocketState state)
{switch (state){case QAbstractSocket::UnconnectedState:labSocketState->setText("socket状态:UnconnectedState");break;case QAbstractSocket::HostLookupState:labSocketState->setText("socket状态:HostLookupState");break;case QAbstractSocket::ConnectingState:labSocketState->setText("socket状态:ConnectingState");break;case QAbstractSocket::ConnectedState:labSocketState->setText("socket状态:ConnectedState");break;case QAbstractSocket::BoundState:labSocketState->setText("socket状态:BoundState");break;case QAbstractSocket::ListeningState:labSocketState->setText("socket状态:ListeningState");break;case QAbstractSocket::ClosingState:labSocketState->setText("socket状态:ClosingState");break;default:break;}
}void MainWindow::on_ReadyRead()
{int nLen = 0;do{char data[1024] = {0};nLen = tcpSocket->readLine(data, 1023);if(nLen > 0){ui->plainTextEdit->appendPlainText(QString::asprintf("[in]: %s", data));}} while(nLen > 0);
}void MainWindow::on_btnSend_clicked()
{QString msg = ui->lineEdit->text();ui->plainTextEdit->appendPlainText("[out] " + msg);ui->lineEdit->clear();ui->lineEdit->setFocus();msg += "\n";QByteArray data = msg.toUtf8();tcpSocket->write(data);
}void MainWindow::on_actConnect_triggered()
{QString IP = ui->comboBox->currentText();int port = ui->spinBox->value();tcpSocket->connectToHost(IP, port);ui->actConnect->setEnabled(false);ui->actDisconnect->setEnabled(true);
}void MainWindow::on_actDisconnect_triggered()
{if(tcpSocket->state() == QAbstractSocket::ConnectedState){tcpSocket->disconnectFromHost();}ui->actConnect->setEnabled(true);ui->actDisconnect->setEnabled(false);
}void MainWindow::on_actClear_triggered()
{ui->plainTextEdit->clear();
}

在这里插入图片描述

三、UDP通信

UDP用户数据报协议,是轻量的、不可靠的、面向数据报、无连接的协议。

1、实现单播/广播程序

在这里插入图片描述

(1)创建项目

(2)添加图标资源

在这里插入图片描述

(3)实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"#include <QHostInfo>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);labSocketState = new QLabel("Socket状态:");labSocketState->setMinimumWidth(200);ui->statusBar->addWidget(labSocketState);QString localIP = getLocalIP();setWindowTitle("Udp收发器:" + localIP);udpSocket = new QUdpSocket(this);connect(udpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),this, SLOT(on_StateChanged(QAbstractSocket::SocketState)));connect(udpSocket, SIGNAL(readyRead()),this, SLOT(on_SocketReadyRead()));
}MainWindow::~MainWindow()
{delete ui;
}QString MainWindow::getLocalIP()
{QString hostName = QHostInfo::localHostName();QHostInfo hostInfo = QHostInfo::fromName(hostName);QString loaclIP;QList<QHostAddress> addList = hostInfo.addresses();foreach (auto aHost, addList){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){if(loaclIP.isEmpty()){loaclIP = aHost.toString();}ui->comboBox->addItem(aHost.toString());}}return loaclIP;
}void MainWindow::on_StateChanged(QAbstractSocket::SocketState state)
{switch (state){case QAbstractSocket::UnconnectedState:labSocketState->setText("socket状态:UnconnectedState");break;case QAbstractSocket::HostLookupState:labSocketState->setText("socket状态:HostLookupState");break;case QAbstractSocket::ConnectingState:labSocketState->setText("socket状态:ConnectingState");break;case QAbstractSocket::ConnectedState:labSocketState->setText("socket状态:ConnectedState");break;case QAbstractSocket::BoundState:labSocketState->setText("socket状态:BoundState");break;case QAbstractSocket::ListeningState:labSocketState->setText("socket状态:ListeningState");break;case QAbstractSocket::ClosingState:labSocketState->setText("socket状态:ClosingState");break;default:break;}
}void MainWindow::on_SocketReadyRead()
{QByteArray datagram;datagram.resize(udpSocket->pendingDatagramSize());QHostAddress peerAddr;unsigned short peerPort;udpSocket->readDatagram(datagram.data(), datagram.size(), &peerAddr, &peerPort);QString str = datagram.data();QString peer = "[From " + peerAddr.toString() + ":" + QString::asprintf("%d", peerPort) + "] ";ui->plainTextEdit->appendPlainText(peer  + str);
}void MainWindow::on_actStart_triggered()
{quint16 port = ui->spinBoxBindPort->value();if(udpSocket->bind(port)){ui->plainTextEdit->appendPlainText("**已绑定成功");ui->plainTextEdit->appendPlainText("**端口:" + QString::number(udpSocket->localPort()));ui->actStart->setEnabled(false);ui->actStop->setEnabled(true);}
}void MainWindow::on_actStop_triggered()
{udpSocket->abort();ui->actStart->setEnabled(true);ui->actStop->setEnabled(false);ui->plainTextEdit->appendPlainText("**已解除绑定");
}void MainWindow::on_actClear_triggered()
{ui->plainTextEdit->clear();
}void MainWindow::on_pushButton_clicked()
{// 单播QString targetIP = ui->comboBox->currentText();quint16 targetPort = ui->spinBoxPort->value();QHostAddress targetAddr(targetIP);QString msg = ui->lineEdit->text();QByteArray data = msg.toUtf8();udpSocket->writeDatagram(data, targetAddr, targetPort);ui->plainTextEdit->appendPlainText("[out] " + msg);ui->lineEdit->clear();ui->lineEdit->setFocus();
}void MainWindow::on_pushButton_2_clicked()
{// 广播quint16 targetPort = ui->spinBoxPort->value();QString msg = ui->lineEdit->text();QByteArray data = msg.toUtf8();udpSocket->writeDatagram(data, QHostAddress::Broadcast, targetPort);ui->plainTextEdit->appendPlainText("[out] " + msg);ui->lineEdit->clear();ui->lineEdit->setFocus();
}

在这里插入图片描述

2、实现组播程序

在这里插入图片描述

(1)拷贝上一个项目

(2)修改控件

在这里插入图片描述

(3)实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);labSocketState = new QLabel("Socket状态:");labSocketState->setMinimumWidth(200);ui->statusBar->addWidget(labSocketState);QString localIP = getLocalIP();setWindowTitle("Udp组播收发器:" + localIP);udpSocket = new QUdpSocket(this);connect(udpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),this, SLOT(on_StateChanged(QAbstractSocket::SocketState)));connect(udpSocket, SIGNAL(readyRead()),this, SLOT(on_SocketReadyRead()));}MainWindow::~MainWindow()
{delete ui;
}QString MainWindow::getLocalIP()
{QString hostName = QHostInfo::localHostName();QHostInfo hostInfo = QHostInfo::fromName(hostName);QString loaclIP;QList<QHostAddress> addList = hostInfo.addresses();foreach (auto aHost, addList){if(aHost.protocol() == QAbstractSocket::IPv4Protocol){if(loaclIP.isEmpty()){loaclIP = aHost.toString();}ui->comboBox->addItem(aHost.toString());}}return loaclIP;
}void MainWindow::on_StateChanged(QAbstractSocket::SocketState state)
{switch (state){case QAbstractSocket::UnconnectedState:labSocketState->setText("socket状态:UnconnectedState");break;case QAbstractSocket::HostLookupState:labSocketState->setText("socket状态:HostLookupState");break;case QAbstractSocket::ConnectingState:labSocketState->setText("socket状态:ConnectingState");break;case QAbstractSocket::ConnectedState:labSocketState->setText("socket状态:ConnectedState");break;case QAbstractSocket::BoundState:labSocketState->setText("socket状态:BoundState");break;case QAbstractSocket::ListeningState:labSocketState->setText("socket状态:ListeningState");break;case QAbstractSocket::ClosingState:labSocketState->setText("socket状态:ClosingState");break;default:break;}
}void MainWindow::on_SocketReadyRead()
{QByteArray datagram;datagram.resize(udpSocket->pendingDatagramSize());QHostAddress peerAddr;unsigned short peerPort;udpSocket->readDatagram(datagram.data(), datagram.size(), &peerAddr, &peerPort);QString str = datagram.data();QString peer = "[From " + peerAddr.toString() + ":" + QString::asprintf("%d", peerPort) + "] ";ui->plainTextEdit->appendPlainText(peer  + str);
}void MainWindow::on_actStart_triggered()
{QString IP = ui->comboBox->currentText();groupAddress = QHostAddress(IP);quint16 groupPort = ui->spinBoxBindPort->value();if(udpSocket->bind(QHostAddress::AnyIPv4, groupPort, QUdpSocket::ShareAddress)){udpSocket->joinMulticastGroup(groupAddress);ui->plainTextEdit->appendPlainText("**加入组播成功");ui->plainTextEdit->appendPlainText("**组播IP:" + IP);ui->plainTextEdit->appendPlainText("**组播端口:" + QString::number(groupPort));ui->actStart->setEnabled(false);ui->actStop->setEnabled(true);ui->comboBox->setEnabled(false);}else{ui->plainTextEdit->appendPlainText("**端口绑定失败");}
}void MainWindow::on_actStop_triggered()
{udpSocket->leaveMulticastGroup(groupAddress);udpSocket->abort();ui->actStart->setEnabled(true);ui->actStop->setEnabled(false);ui->comboBox->setEnabled(true);ui->plainTextEdit->appendPlainText("**已退出组播,解除端口绑定");
}void MainWindow::on_actClear_triggered()
{ui->plainTextEdit->clear();
}void MainWindow::on_btnSend_clicked()
{QString targetIP = ui->comboBox->currentText();quint16 targetPort = ui->spinBoxBindPort->value();QHostAddress targetAddr(targetIP);QString msg = ui->lineEdit->text();QByteArray data = msg.toUtf8();udpSocket->writeDatagram(data, targetAddr, targetPort);ui->plainTextEdit->appendPlainText("[out] " + msg);ui->lineEdit->clear();ui->lineEdit->setFocus();
}

在这里插入图片描述

四、HTTP通信

1、相关类

QNetworkRequest,通过一个URL地址发起网络请求,也保存网络请求信息。
QNetworkAccessManager,用于协调网络操作,在QNetworkRequest发起一个网络请求后,负责发送网络请求,创建网络响应。
QNwtworkReply,网络请求的响应。

1、实现基于http协议文件下载

在这里插入图片描述

(1)创建项目

在这里插入图片描述

(2)实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QMessageBox>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);
}MainWindow::~MainWindow()
{delete ui;
}#include <QDesktopServices>
void MainWindow::on_finished()
{QFileInfo fileInfo;fileInfo.setFile(downloadFile->fileName());downloadFile->close();delete downloadFile;downloadFile = nullptr;reply->deleteLater();reply = nullptr;if(ui->checkBox->isChecked()){QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absolutePath()));ui->btnDownload->setEnabled(true);}
}void MainWindow::on_readyRead()
{downloadFile->write(reply->readAll());
}void MainWindow::on_downloadProgress(qint64 readBytes, qint64 totalBytes)
{ui->progressBar->setMaximum(totalBytes);ui->progressBar->setValue(readBytes);
}void MainWindow::on_btnDownload_clicked()
{QString strUrl = ui->lineEditUrl->text();if(strUrl.isEmpty()){QMessageBox::information(this, "error", "请输入正确地址");return;}QUrl newUrl = QUrl::fromUserInput(strUrl);if(!newUrl.isValid()){QMessageBox::information(this, "error",QString::asprintf("无效的URL:%s\n错误信息: %s", strUrl.data(), newUrl.errorString().data()));return;}QString tempDir = ui->lineEditSavePath->text();if(tempDir.isEmpty()){QMessageBox::information(this, "error", "保存路径无效");return;}QString fullFileName = tempDir + newUrl.fileName();if(QFile::exists(fullFileName)){QFile::remove(fullFileName);}downloadFile = new QFile(fullFileName);if(!downloadFile->open(QIODevice::WriteOnly)){QMessageBox::information(this, "error", "文件打开失败:" + fullFileName);return;}ui->btnDownload->setEnabled(false);reply = networkManager.get(QNetworkRequest(newUrl));connect(reply, SIGNAL(finished()), this, SLOT(on_finished()));connect(reply, SIGNAL(readyRead()), this, SLOT(on_readyRead()));connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(on_downloadProgress(qint64, qint64)));
}void MainWindow::on_btnDefaultPath_clicked()
{QString curPath = QDir::currentPath();QDir dir(curPath);QString sub("temp");dir.mkdir(sub);ui->lineEditSavePath->setText(dir.path() + "/" + sub + "/");
}

在这里插入图片描述

五、打包程序

将指定程序打包,将依赖库打包进目录
D:\Qt\Qt5.13.0\5.13.0\mingw73_64\bin\windeployqt.exe E:/XXX/xxx.exe

在这里插入图片描述

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

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

相关文章

Linux系统加固:限制用户对资源的使用禁止IP源路由更改主机解析地址的顺序设置umask值

Linux系统加固&#xff1a;限制用户对资源的使用&禁止IP源路由&更改主机解析地址的顺序&设置umask值 1.1 限制用户对资源的使用1.2 禁止IP源路由1.3 更改主机解析地址的顺序1.4 禁止ip路由转发1.5 设置umask值 &#x1f496;The Begin&#x1f496;点点关注&#x…

虚拟化介绍

虚拟化理论介绍 什么是虚拟化: 虚拟化&#xff08;Virtualization&#xff09;技术最早出现在 20 世纪 60 年代的 IBM 大型机系统。 在70年代的 System 370 系列中逐渐流行起来&#xff0c;这些机器通过一种叫虚拟机监控器&#xff08;Virtual Machine Monitor&#xff0c;V…

浅谈 Linux进程回收、wait、waitpid函数

文章目录 前言进程回收wait 函数进程回收 相关的宏函数介绍waitpid 函数 前言 本文介绍 进程回收 的概念、相关宏函数、wait 函数 以及 waitpid 函数的使用方式。 进程回收 一个进程终止时会关闭所有文件描述符&#xff0c;释放在用户空间分配的内存&#xff0c;但它的 PCB …

RocketMQ安装

mq服务端安装配置启动把windows做成服务 mq管理界面安装配置启动 mq服务端 安装 RocketMQ下载地址 配置 ROCKETMQ_HOME D:\google-d\rocketmq-all-5.2.0-bin-release启动 # bin目录cmd输入 start mqnamesrv.cmd把windows做成服务 http://t.csdnimg.cn/qd2RD mq管理界面 …

CentOS7设置虚拟机语言为中文

1.查看本地安装的语言 locale -a 是一个Linux命令&#xff0c;用于列出系统中可用的所有区域设置&#xff08;locales&#xff09;它包含了各种语言和地区的不同设置。 打开终端&#xff08;右键open terminal&#xff09;输入 locale -a 查看本地安装的语言&#xff1a; 其中z…

深入理解与应用工厂方法模式

文章目录 一、模式概述**二、适用场景****三、模式原理与实现****四、采用工厂方法模式的原因****五、优缺点分析****六、与抽象工厂模式的比较**总结 一、模式概述 ​ 工厂方法模式是一种经典的设计模式&#xff0c;它遵循面向对象的设计原则&#xff0c;特别是“开闭原则”&…

C语言-指针(上)

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、pandas是什么&#xff1f;二、使用步骤 1.引入库2.读入数据总结 前言 本篇文章将为大家介绍C语言中的核心内容-指针&#xff0c;指针在C语言的中知识内容比…

详解 JavaScript 中的数组

详解 JavaScript 中的数组 创建数组 注&#xff1a;在JS中的数组不要求元素的类型&#xff0c;元素类型可以一样&#xff0c;也可以不一样 1.使用 new 关键字创建 let array new Array()2.使用字面量方式创建(常用) let array1 [1,2,3,"4"]获取数组元素 使用下…

Python 教学平台,支持“多班教学”的课程授课方式|ModelWhale 版本更新

龙行龘龘、前程朤朤&#xff0c;ModelWhale 新一轮的版本更新&#xff0c;期待为大家带来更优质的使用体验。 本次更新中&#xff0c;ModelWhale 主要进行了以下功能迭代&#xff1a; 新增 课程&#xff08;包括课件、作业、算力&#xff09;按班级管理&#xff08;团队版✓ …

Linux笔记-1

概述 简介 Linux是现在服务器上最常用的操作系统(OS - Operating system) - 所谓的操作系统本质上也是一个软件&#xff0c;是一个可以运行其他软件的容器如果一台服务器&#xff0c;没有安装操作系统&#xff0c;此时称之为裸机。裸机可以使用&#xff0c;在使用的时候需要使…

TCP与UDP基础

思维导图&#xff1a; TCP&#xff1a; 服务器 #include<myhead.h> #define SER_IP "192.168.252.163" #define SER_PORT 6666 int main(int argc, const char *argv[]) {//&#xff11;、创建用于监听的套接字int sfd-1;sfdsocket(AF_INET,SOCK_STREAM,0);/…

泰迪智能科技企业数据挖掘平台使用场景

企业数据挖掘平台助力企业数据挖掘&#xff0c;数据挖掘平台也在多个领域发挥着重要的作用。 企业数据挖掘平台具有数据抓取、数据清洗、数据分析、机器学习等多项功能&#xff0c;广泛应用于企业的各个领域&#xff0c;包括&#xff1a;金融行业、医疗行业、交通领域、教育、制…