QT6实现局域网内文件传输工具

一.功能实现效果图

文件保存到项目包路径

二.代码参考源码

pro文件

QT       += core gui
QT       += network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++17

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#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

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

widget.h       

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QTcpSocket>
#include <QTcpServer>
#include <QFile>
#include <QTextEdit>
#include <QProgressBar>

class Widget : public QWidget
{
    Q_OBJECT

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

    void Init();

private slots:
    void onTcpConnected();
    void onConnectClicked();
    void ServerNewConnect();
    void SocketReadData();
    void onOpenFileClicked();
    void onSendClicked();
    void updateClientProgress(qint64 numBytes);

private:
    QPushButton *m_pConnectBtn=nullptr;
    QLineEdit *m_pIpAddressEdit=nullptr;
    QLineEdit *m_pPortEdit=nullptr;
    QWidget *m_pTitleWgt=nullptr;

    QLineEdit *m_pFilePathEdit=nullptr;
    QPushButton *m_pOpenFileBtn=nullptr;
    QPushButton *m_pSendBtn=nullptr;

    QTextEdit *m_pTextEdit=nullptr;

    QProgressBar *m_pReceiverBar=nullptr;
    QProgressBar *m_pSendBar=nullptr;


    QTcpSocket *m_pTcpSocket=nullptr;
    QTcpServer *m_pTcpServer=nullptr;
    QTcpSocket *m_pTcpServerSocket=nullptr;
    //------receiver
    qint64 m_bytesReceived;
    qint64 m_fileNameSize;
    qint64 m_totalBytes;
    QString m_fileName;
    QFile *m_localFile;
    QByteArray m_inBlock;

    //send
    QFile *m_ClientlocalFile;
    QString m_ClientfileName;
    qint64 m_ClienttotalBytes;
    qint64 m_ClientbytesWritten=0;
    qint64 m_ClientbytesToWrite;
    qint64 m_ClinetpayloadSize;
    QByteArray m_ClientoutBlock;
};
#endif // WIDGET_H

widget.cpp 

#include "widget.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QValidator>
#include <QMessageBox>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    this->resize(800,600);
    Init();
    m_pTcpSocket=new QTcpSocket(this);
    connect(m_pTcpSocket,&QTcpSocket::connected,this,&Widget::onTcpConnected);  //若连接成功,则触发此信号
    connect(m_pTcpSocket,SIGNAL(bytesWritten(qint64)),this,SLOT(updateClientProgress(qint64))); //发送数据

    m_pTcpServer=new QTcpServer(this);
    m_totalBytes=0;
    m_bytesReceived=0;
    m_fileNameSize=0;
    connect(m_pTcpServer,&QTcpServer::newConnection,this,&Widget::ServerNewConnect);
    if(!m_pTcpServer->listen(QHostAddress::Any, 2021))   //端口为2021
    {
        QMessageBox::warning(this,"Warning",m_pTcpServer->errorString(),QMessageBox::Ok);
        return;
    }
}

Widget::~Widget()
{
}

void Widget::Init()
{
    m_pConnectBtn=new QPushButton(tr("Connect"),this);
    m_pIpAddressEdit=new QLineEdit(this);
    m_pPortEdit=new QLineEdit(this);
    m_pPortEdit->setValidator(new QIntValidator());
    m_pTitleWgt=new QWidget(this);
    m_pIpAddressEdit->setFixedWidth(200);
    m_pPortEdit->setFixedWidth(200);
    m_pConnectBtn->setFixedSize(100,25);
    QLabel *ipLabel=new QLabel(tr("IpAddress:"),this);
    QLabel *portLabel=new QLabel(tr("Port:"),this);
    ipLabel->setFixedWidth(60);
    portLabel->setFixedWidth(40);
    QHBoxLayout *titleLayout=new QHBoxLayout(this);
    titleLayout->addWidget(ipLabel);
    titleLayout->addWidget(m_pIpAddressEdit);
    titleLayout->addWidget(portLabel);
    titleLayout->addWidget(m_pPortEdit);
    titleLayout->addWidget(m_pConnectBtn);
    titleLayout->setContentsMargins(5,5,5,5);
    titleLayout->setSpacing(10);
    titleLayout->addStretch();
    m_pTitleWgt->setFixedHeight(40);
    m_pTitleWgt->setLayout(titleLayout);

    m_pIpAddressEdit->setText("192.168.2.110");
    m_pPortEdit->setText("2021");

    m_pPortEdit->setEnabled(false);

    m_pFilePathEdit=new QLineEdit(this);
    m_pOpenFileBtn=new QPushButton(tr("Open File"),this);
    m_pSendBtn=new QPushButton(tr("Send"));

    m_pFilePathEdit->setFixedWidth(500);
    m_pOpenFileBtn->setFixedSize(100,25);
    m_pSendBtn->setFixedSize(100,25);

    m_pSendBtn->setEnabled(false);

    QWidget *bottomWgt=new QWidget(this);
    QHBoxLayout *bottomLayout=new QHBoxLayout(this);
    bottomLayout->addWidget(m_pFilePathEdit);
    bottomLayout->addWidget(m_pOpenFileBtn);
    bottomLayout->addWidget(m_pSendBtn);
    bottomLayout->setContentsMargins(5,5,5,5);
    bottomLayout->setSpacing(5);
    bottomLayout->addStretch();
    bottomWgt->setLayout(bottomLayout);

    m_pTextEdit=new QTextEdit(this);

    QLabel *receiverLabel=new QLabel(tr("Receiver Speed"),this);
    QLabel *SendLabel=new QLabel(tr("Send Speed"),this);
    receiverLabel->setFixedWidth(100);
    SendLabel->setFixedWidth(100);
    m_pReceiverBar=new QProgressBar(this);
    m_pSendBar=new QProgressBar(this);
    m_pReceiverBar->setFixedSize(300,30);
    m_pSendBar->setFixedSize(300,30);
    m_pReceiverBar->setOrientation(Qt::Horizontal);
    m_pSendBar->setOrientation(Qt::Horizontal);

    QWidget *receiverBarWgt=new QWidget(this);
    QHBoxLayout *receiverBarLayout=new QHBoxLayout(this);
    receiverBarLayout->addWidget(receiverLabel);
    receiverBarLayout->addWidget(m_pReceiverBar);
    receiverBarLayout->addStretch();
    receiverBarLayout->setSpacing(5);
    receiverBarWgt->setLayout(receiverBarLayout);

    QWidget *sendBarWgt=new QWidget(this);
    QHBoxLayout *sendBarLayout=new QHBoxLayout(this);
    sendBarLayout->addWidget(SendLabel);
    sendBarLayout->addWidget(m_pSendBar);
    sendBarLayout->addStretch();
    sendBarLayout->setSpacing(5);
    sendBarWgt->setLayout(sendBarLayout);

    connect(m_pConnectBtn,&QPushButton::clicked,this,&Widget::onConnectClicked);
    connect(m_pOpenFileBtn,&QPushButton::clicked,this,&Widget::onOpenFileClicked);
    connect(m_pSendBtn,&QPushButton::clicked,this,&Widget::onSendClicked);

    QVBoxLayout *mainLayout=new QVBoxLayout(this);
    mainLayout->addWidget(m_pTitleWgt);
    mainLayout->addWidget(bottomWgt);
    mainLayout->addWidget(receiverBarWgt);
    mainLayout->addWidget(sendBarWgt);
    mainLayout->addWidget(m_pTextEdit);
    mainLayout->setContentsMargins(0,0,0,0);
    mainLayout->addStretch();
    this->setLayout(mainLayout);

}

void Widget::onTcpConnected()
{
    m_pTextEdit->append("Connect Server Success!");
}

void Widget::onConnectClicked()
{
    QString strip=m_pIpAddressEdit->text();
    QString strport=m_pPortEdit->text();
    if(strip!=""&&strport!="")
    {
        m_pTcpSocket->connectToHost(strip,strport.toInt());  //请求连接
    }
    else
    {
        QMessageBox::warning(this,"Warning","IpAddress or Port is Null",QMessageBox::Ok);
    }
}

void Widget::ServerNewConnect()
{
    m_pTcpServerSocket = m_pTcpServer->nextPendingConnection(); //服务端接受消息
    QObject::connect(m_pTcpServerSocket, &QTcpSocket::readyRead, this, &Widget::SocketReadData);
    m_pTextEdit->append("Connect Client Success");

}

void Widget::SocketReadData()
{
    QDataStream in(m_pTcpServerSocket);
    in.setVersion(QDataStream::Qt_5_11);
    if (m_bytesReceived<=sizeof(qint64)*2){
        if((m_pTcpServerSocket->bytesAvailable()>=sizeof(qint64)*2)&&(m_fileNameSize==0)){
            in>>m_totalBytes>>m_fileNameSize;
            m_bytesReceived +=sizeof(qint64)*2;
        }

        if((m_pTcpServerSocket->bytesAvailable()>=m_fileNameSize)&&(m_fileNameSize!=0)){
            in>>m_fileName;
            m_bytesReceived+=m_fileNameSize;
            m_localFile = new QFile(m_fileName);
            if (!m_localFile->open(QFile::WriteOnly)){
                qDebug() << "server: open file error!";
                return;
            }
        }
        else{
            return;
        }
    }

    if(m_bytesReceived<m_totalBytes) {
        m_bytesReceived+=m_pTcpServerSocket->bytesAvailable();
        m_inBlock = m_pTcpServerSocket->readAll();
        m_localFile->write(m_inBlock);
        m_inBlock.resize(0);
    }


    m_pReceiverBar->setMaximum(m_totalBytes);
    m_pReceiverBar->setValue(m_bytesReceived);

    if (m_bytesReceived==m_totalBytes){
        m_localFile->close();
        QString strSuccess=QString("File %1 ReceiverSucess").arg(m_fileName);
        m_pTextEdit->append(strSuccess);
        m_pTcpServerSocket->close();
        m_totalBytes=0;
        m_bytesReceived=0;
        m_fileNameSize=0;
    }
}

void Widget::onOpenFileClicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    "/home",
                                                    tr("File (*.*)"));
    if(fileName!="")
    {
        m_ClientfileName=fileName;
        m_pSendBtn->setEnabled(true);
        m_pFilePathEdit->setText(fileName);
    }
}

void Widget::onSendClicked()
{
    m_ClientoutBlock.clear();
    m_ClientlocalFile=new QFile(m_ClientfileName);
    if(!m_ClientlocalFile->open(QFile::ReadOnly)){
        qDebug()<<"client:open file error!";
        return;
    }
    m_ClienttotalBytes=m_ClientlocalFile->size();
    QDataStream sendOut(&m_ClientoutBlock,QIODevice::WriteOnly);
    sendOut.setVersion(QDataStream::Qt_5_11);
    QString currentFileName=m_ClientfileName.right(m_ClientfileName.size()-m_ClientfileName.lastIndexOf('/')-1);
    sendOut<<qint64(0)<<qint64(0)<<currentFileName;
    m_ClienttotalBytes+=m_ClientoutBlock.size();
    sendOut.device()->seek(0);
    sendOut<<m_ClienttotalBytes<<qint64(m_ClientoutBlock.size()-sizeof(qint64)*2);
    m_ClientbytesToWrite=m_ClienttotalBytes-m_pTcpSocket->write(m_ClientoutBlock);
    m_ClientoutBlock.resize(0);
}

void Widget::updateClientProgress(qint64 numBytes)
{
    m_ClientbytesWritten+=(int)numBytes;
    if(m_ClientbytesToWrite>0){
        m_ClientoutBlock=m_ClientlocalFile->read(qMin(m_ClientbytesToWrite,m_ClinetpayloadSize));
        m_ClientbytesToWrite-=(int)m_pTcpSocket->write(m_ClientoutBlock);
        m_ClientoutBlock.resize(0);
    }
    else{
        m_ClientlocalFile->close();
    }

    m_pSendBar->setMaximum(m_ClienttotalBytes);
    m_pSendBar->setValue(m_ClientbytesWritten);

    if(m_ClientbytesWritten==m_ClienttotalBytes){
        QString sendSuccess=QString("Send File %1 Success").arg(m_fileName);
        m_pTextEdit->append(sendSuccess);
        m_ClientlocalFile->close();
        m_pTcpSocket->close();
        m_ClientbytesWritten=0;
    }
}


main.cpp

#include "widget.h"

#include <QApplication>

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

UI文件无需编辑

功能说明

一款利用QT环境搭建的文件传输小工具,功能仅限于局域网内使用tcp传输文件,同一网络下使用。

局域网中进行文件传输,可以通过多种方式实现。其中一种方式是使用自己写的一个在Ubuntu下运行的局域网传输文件工具。用户可以在该工具中输入对方的IP地址,然后选择要发送的文件,发送过程中会显示传输进度条。这个工具是在QT4.8下进行开发的。 另外,你也可以通过在Ubuntu中挂载Windows共享文件夹的方式进行局域网文件传输。首先,在Windows中创建共享文件夹,并在Ubuntu中安装mount.cifs软件包。然后,在Ubuntu中创建共享文件夹并挂载Windows共享文件夹,即可进行文件传输。具体的操作步骤如下: 1. 在Windows中创建共享文件夹,设置共享权限,并记录共享文件夹的网络路径和局域网的IP地址。 2. 在Ubuntu中安装mount.cifs软件包。 3. 在Ubuntu中创建共享文件夹,并使用mount.cifs命令挂载Windows共享文件夹到Ubuntu中的共享文件夹路径。 4. 输入本机密码和共享主机密码,即可完成挂载。 通过以上步骤,你可以在Ubuntu中实现局域网文件传输。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【windows-ubuntu通过局域网连接共享文件夹以传输文件】](https://blog.csdn.net/Phycho_/article/details/130929280)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [在Ubuntu下运行的局域网传输文件工具,程序环境是在QT4.8。](https://download.csdn.net/download/nrahbsqtym/9847199)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [windows与ubuntu在同一局域网如何共享文件](https://blog.csdn.net/weixin_41099940/article/details/124047855)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PYGG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值