最近因为一个事情很恼火,因为办公需要用到企业微信,但是企业微信只能在一个电脑上登陆,所以当别人发文件给你的时候,你只能一个电脑接收,创建共享文件夹也很麻烦,每次都需要去访问,很麻烦。所以准备自己写一个文件传输小工具。
功能就是能实现文件的双向传输,即客户端能传给服务端,服务端可以传给客户端。
使用的tcp通信,其实就是发消息,但是组合数据我是借鉴了IT1995大神写的代码。
先看下效果图

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

本地文件下出现了一份传输的文件。
直接看代码
.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_OBJECTpublic: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;//------receiverqint64 m_bytesReceived;qint64 m_fileNameSize;qint64 m_totalBytes;QString m_fileName;QFile *m_localFile;QByteArray m_inBlock;//sendQFile *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制作一个简易的传输文件小工具相关推荐

  1. python温度转换_一步一步教会你,详解用Python实现一个简易的温度换算GUI小工具...

    今天,我们来使用Python完成一个小工具的制作.很简单,就是对于摄氏温度和华氏温度的相互换算.但是,我们的目的是复习一下之前学过的Python中tkinter的小内容. 复习下前面的知识 先来看下今 ...

  2. 利用Qt制作一个简易聊天软件

    需求分析 即时通讯软件是通过即时通讯技术来实现在线聊天.交流的软件.需要完成基本的通信需求及工作场景需求. 架构分析 截图展示 项目简介 我们编写的即时通信软件叫做SeeU,它是一款基于Qt开发平台, ...

  3. python制作软件excel_利用Python制作一个 截图+Excel操作浏览器小工具

    代码如下: GetData.py import xlrd class ReadExcel(): def __init__(self,file): self.open_excel = xlrd.open ...

  4. 使用Java制作一个简易的远控终端

    使用Java制作一个简易的远控终端 远控终端的本质 1.服务端(攻击者)传输消息 ----> socket连接 ----> 客户端(被攻击者)接收消息 2.客户端执行消息内容(即执行服务端 ...

  5. 使用python制作一个简易的远控终端

    使用python制作一个简易的远控终端 远控终端的本质 1.服务端(攻击者)传输消息 ----> socket连接 ----> 客户端(被攻击者)接收消息 2.客户端执行消息内容(即执行服 ...

  6. OpenCV探索之路(二十五):制作简易的图像标注小工具

    搞图像深度学习的童鞋一定碰过图像数据标注的东西,当我们训练网络时需要训练集数据,但在网上又没有找到自己想要的数据集,这时候就考虑自己制作自己的数据集了,这时就需要对图像进行标注.图像标注是件很枯燥又很 ...

  7. 用Python制作一个简易的计时器

    前言 今天又带来个小玩意 - 用Python制作一个简易的计时器 这个其实也能自定义一些东西的 就比如名字 颜色啥的 自己看着改就行 有想法的朋友也能自己再写写改改出其他的小功能 效果展示 实现代码 ...

  8. 使用Qt写一个简单的五子棋单机小游戏

    使用Qt写一个简单的五子棋单机小游戏 刚学,不够专业请勿喷,有不对的地方还请指出,我渴望进步!现在贴出这个游戏我原创的所有代码.希望可以帮到有需要的人. 游戏界面: 因为后面添加了.wav的音频文件, ...

  9. 制作一个简易的计算器

    这里写自定义目录标题 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一 ...

  10. 制作一个有趣的涂鸦物联网小项目(涂鸦模组SDK开发 CBU BK7231N WiFi+蓝牙模组 HSV彩色控制)

    实现的功能: l  APP控制月球灯 l  本地月球灯控制 l  APP控制"大白"颜色,实现各种颜色变身 l  门状态传感器状态APP显示 l  网络状态指示灯,连接服务器长亮, ...

最新文章

  1. Linux05-进程管理
  2. 迁移到阿里云后,NTKO控件报存word 报文件存取错误,请检查网络传输。
  3. python 如果你的年龄大于18_python基础
  4. [转]消息队列软件大比拼
  5. 【GitHub】GitHub 的 Pull Request 和 GitLab 的 Merge Request 有区别吗?
  6. Spring事务隔离级别,事务传播行为
  7. android插件化-获取apkplug框架已安装插件-03
  8. 如何整一个厉害的产品slogan?
  9. 问题的分析与解决(培训总结)
  10. 十步一拆:iPhone4S拆机十步曲
  11. 酒店电视方案 酒店建设高清数字电视系统的解决方案
  12. Redhat8: SCTP: type= 5 errno= <0x5e> Socket type not supported
  13. 新一代大数据技术架构
  14. FastReport VCL 2022.3
  15. 从零到大神,135排版训练营给你实实在在的排版!
  16. MIUI11Android系统耗电,小米MIUI系统升级11,网友表示很费电,学习这个省电方法够你用三天!...
  17. 1602液晶显示程序
  18. (jsp/html)网页上嵌入播放器(常用播放器代码整理) http://www.jb51.net/article/37267.htm...
  19. Reading Ingestion —— Bigtable: A Distributed Storage System for Structured Data
  20. 战斗在风口:社区团购从0到1实战运营笔记

热门文章

  1. 从优秀到卓越 pdf_演讲口才培训:演讲能力是卓越领导者需要具备的能力
  2. 主键冲突报什么代码_MySQL主键设计
  3. python修改html,Python爬虫精简步骤 HTML基础
  4. java jax ws_Java 7是否包含JAX-WS实现或API?
  5. ccf-csp认证历年真题(持续更新)
  6. 成都-地点-文创-宽窄巷子:宽窄巷子
  7. 计算几何——交点、面积的计算
  8. GoodUserInterface 模仿页面功能
  9. Unity性能优化专题---腾讯牛人分享经验
  10. 『ORACLE』 Linux和oracle用户下的常用命令(11g)