欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于QT制作一个简易的传输文件小工具

程序员文章站 2022-06-16 10:56:32
最近因为一个事情很恼火,因为办公需要用到企业微信,但是企业微信只能在一个电脑上登陆,所以当别人发文件给你的时候,你只能一个电脑接收,创建共享文件夹也很麻烦,每次都需要去访问,很麻烦。所以准备自己写一个...

最近因为一个事情很恼火,因为办公需要用到企业微信,但是企业微信只能在一个电脑上登陆,所以当别人发文件给你的时候,你只能一个电脑接收,创建共享文件夹也很麻烦,每次都需要去访问,很麻烦。所以准备自己写一个文件传输小工具。

功能就是能实现文件的双向传输,即客户端能传给服务端,服务端可以传给客户端。

使用的tcp通信,其实就是发消息,但是组合数据我是借鉴了it1995大神写的代码。

先看下效果图

基于QT制作一个简易的传输文件小工具

可以看到既可以接受文件也可进行发送文件,只要2台电脑在统一局域网内,就可发送和接受数据。

基于QT制作一个简易的传输文件小工具

本地文件下出现了一份传输的文件。

直接看代码

.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

.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->setmargin(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->setmargin(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->setmargin(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;
    }
}


这个小工具我会一直用的 

到此这篇关于基于qt制作一个简易的传输文件小工具的文章就介绍到这了,更多相关qt传输文件工具内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!