QT笔记之VS2012 TCP传送文件
注意:工程监理后,因为用到网路,所以要加入对应的库
服务器:
.h
#ifndef TCPFILE_H
#define TCPFILE_H #include <QtWidgets/QWidget>
#include "ui_tcpfile.h"
#include <QtNetwork/QTcpServer>//监听套接字
#include <QtNetwork/QTcpSocket>//通信套接字
#include <QFile>
#include <QTimer> class TCPFile : public QWidget
{
Q_OBJECT public:
TCPFile(QWidget *parent = );
~TCPFile(); void SendData();//发送文件数据函数 private slots:
void on_buttonSelect_clicked(); void on_buttonSend_clicked(); private:
Ui::TCPFileClass ui; QTcpServer* tcpServer;//监听套接字
QTcpSocket* tcpSocket;//通信套接字 QFile file;//文件对象
QString filename;//文件名字
qint64 filesize;//文件大小
qint64 sendsize;//已发送文件大小 QTimer timer;//定时器
}; #endif // TCPFILE_H
.cpp
#include "tcpfile.h"
#include <QTextCodec>
#include <QFileDialog>//选择文件对话框
#include <QDebug>
#include <QFileInfo>//文件信息 TCPFile::TCPFile(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this); //监听套接字
tcpServer = new QTcpServer(this); //监听
tcpServer->listen(QHostAddress::Any,); QTextCodec *codec = QTextCodec::codecForLocale();//解决中文乱码 QString Titleinfo = codec->toUnicode("服务器端口为:8888"); setWindowTitle(Titleinfo); //建立连接之前两个按钮不可用
ui.buttonSelect->setEnabled(false);
ui.buttonSend->setEnabled(false); //如果客户端和服务器连接
//tcpServer会自动触发 newConnection() connect(tcpServer,&QTcpServer::newConnection,
[=]()
{
//取出建立好连接的套接字
tcpSocket = tcpServer->nextPendingConnection(); //获取对方的ip和port
QString strIP = tcpSocket->peerAddress().toString();
quint16 port = tcpSocket->peerPort(); QString str = QStringLiteral("[%1,%2] 成功连接").arg(strIP).arg(port);
//str = codec->toUnicode(str); ui.textEdit->setText(str);//显示到编辑框 //成功连接后 选择按钮可用 ui.buttonSelect->setEnabled(true);
}
); connect(&timer,&QTimer::timeout,
[=]()
{
//关闭定时器
timer.stop();
SendData();
}
);
} TCPFile::~TCPFile()
{ } void TCPFile::on_buttonSelect_clicked()
{
QString filepath = QFileDialog::getOpenFileName(this,"open","../"); if(!filepath.isEmpty())
{
//文件路径有效
//只读方式打开文件
filename.clear();
filesize = ; QFileInfo info(filepath);//获取文件信息
filename = info.fileName();
filesize = info.size(); sendsize = ;//发送文件的大小 file.setFileName(filepath); //打开文件 bool isOk = file.open(QIODevice::ReadOnly); if(false == isOk)
{
qDebug() << "只读方式打开文件失败";
}
else
{
//提示打开文件的路径
ui.textEdit->append(filepath);
ui.buttonSelect->setEnabled(false);
ui.buttonSend->setEnabled(true); }
}
} void TCPFile::on_buttonSend_clicked()
{
//先发送文件头部信息
QString head = QString("%1##%2").arg(filename).arg(filesize);//自定义文件头部 //发送头部信息
qint64 len = tcpSocket->write(head.toUtf8());
if(len > )//头部信息发送成功
{
//发送真正的文件信息
//防止TCP粘包文件
//需要通过定时器延时 20ms timer.start();
}
else
{
qDebug() << "头部信息发送失败 115";
file.close(); ui.buttonSelect->setEnabled(true);
ui.buttonSend->setEnabled(false);
}
} void TCPFile::SendData()
{
qint64 len = ; do
{
//每次发送数据的大小
char buf[*] = {};
len = ; //往文件中读数据
len = file.read(buf,sizeof(buf));
//发送数据 读多少 发送多少 //发送多好
len = tcpSocket->write(buf,len);
sendsize += len;
}while(len > ); if(sendsize == filesize)
{
ui.textEdit->append("file finshed");
file.close(); //把客户端断开连接
tcpSocket->disconnectFromHost();
tcpSocket->close();
}
}
客户端
.h
#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H #include <QWidget>
#include "ui_clientwidget.h"
#include <QtNetwork/QTcpSocket>//通信套接字
#include <QFile> class ClientWidget : public QWidget
{
Q_OBJECT public:
ClientWidget(QWidget *parent = );
~ClientWidget(); private slots:
void on_buttonConnect_clicked(); private:
Ui::ClientWidget ui; QTcpSocket* tcpSocket;//通信套接字 QFile file;//文件对象
QString filename;//文件名字
qint64 filesize;//文件大小
qint64 recvsize;//已接收文件大小 bool isHead;//是否是头
}; #endif // CLIENTWIDGET_H
.cpp
#include "clientwidget.h"
#include <QMessageBox>
#include <QHostAddress>
#include <QTextCodec> ClientWidget::ClientWidget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this); tcpSocket = new QTcpSocket(this); setWindowTitle(QStringLiteral("客户端")); isHead = true; QTextCodec *codec = QTextCodec::codecForLocale();//解决中文乱码 connect(tcpSocket,&QTcpSocket::readyRead,
[=]()
{
//取出接收到的东西
QByteArray buf = tcpSocket->readAll(); if (isHead)
{//接收头
isHead = false;
//解析头部信息 QString buf = "hello##1024"; 文件名为 "hello" 大小为 1024
// QString str ="hello##1024";
//str.section("##",0,0); 取出 "hello"
//str.section("##",1,1); 取出 "1024" filename = QString(buf).section("##", , );
filesize = QString(buf).section("##", , ).toInt();
recvsize = ; //初始化
//打开文件 file.setFileName(filename); bool isOk = file.open(QIODevice::WriteOnly); if (false == isOk)
{
QMessageBox::information(this,"打开","文件打开失败");
} }
else
{
//文件信息
qint64 len = file.write(buf); recvsize += len; if (recvsize == filesize)
{
file.close();
QString title = codec->toUnicode("完成");
QString info = codec->toUnicode("接收完成");
QMessageBox::information(this,title,info); //断开连接
tcpSocket->disconnectFromHost();
tcpSocket->close();
} }
}
);
} ClientWidget::~ClientWidget()
{ } void ClientWidget::on_buttonConnect_clicked()
{
//获取服务器的IP和端口 QString strIP = ui.lineEditIP->text();
quint16 port = ui.lineEditPort->text().toInt(); tcpSocket->connectToHost(QHostAddress(strIP),port);
}
main文件
#include "tcpfile.h"
#include <QtWidgets/QApplication>
#include "clientwidget.h" int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TCPFile w;
w.show(); ClientWidget cw;
cw.show(); return a.exec();
}
运行效果:
第一步:
第二步:
第三步:
第四步:
QT笔记之VS2012 TCP传送文件的更多相关文章
- 读书笔记——《图解TCP/IP》(1/4)
读书笔记——<图解TCP/IP>(1/4) 经典摘抄 第一章 网络基础知识 1.独立模式:计算机未连接到网络,各自独立使用的方式. 2.广域网 WAN 局域网 LAN 城域网 MAN 3. ...
- SZ,RZ传送文件
linux 和window之间通过xshell的命令 SZ,RZ传送文件:
- python使用简单http协议来传送文件
python使用简单http协议来传送文件!在ubuntu环境下,局域网内可以使用nc来传送文件,也可以使用基于Http协议的方式来下载文件我们可以使用python -m SimpleHTTPServ ...
- QT运行时加载UI文件
写QT程序里运行时加载UI文件,代码如下: 点击(此处)折叠或打开 #include "keyboard.h" #include <QtUiTools> #incl ...
- Linux SSH 远程操作与传送文件
操作系统:centos 6.5 x64 一.远程连接:在进行linux 的 ssh远程操作前,一定要确认linux 是否安装了 openssh-clients,为了方便起见,一般用yum安装即可:# ...
- SCP传送文件时提示No ECDSA host key is known forx.x.x.x and you have requested strict checking.问题的解决办法
在使用SCP向其他设备传送文件时,打印如下错误: No ECDSA host key is known for x.x.x.x and you have requested strict checki ...
- Delphi IdTCPClient IdTCPServer 点对点传送文件
https://blog.csdn.net/luojianfeng/article/details/53959175 2016年12月31日 23:40:15 阅读数:2295 Delphi ...
- InstallShield 2015 LimitedEdition VS2012 运行bat文件
转载:http://www.cnblogs.com/fengwenit/p/4271150.html 运行bat文件 网上很多介绍如何运行bat的方法,但我这个是limted 版本,不适用. 1. ...
- Qt SD卡 文件系统挂载、文件预览
/********************************************************************************** * Qt SD卡 文件系统挂载. ...
随机推荐
- 修复Magento SQLSTATE[23000]: Integrity constraint
magneto在意外情况下报错Magento SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry,出现这个问题最 ...
- 利用pip安装模块(以安装pyperclip为例)
>任务:利用pip安装pyperclip模块 >前提:你已经在你的电脑里面安装啦Python2.7的Windows版本,并且已经配置了环境变量 >实现步骤 >>打开你的P ...
- C# (灰度)加权平均法将图片转换为灰度图
private Bitmap ToG(string file) { using (Bitmap o = new Bitmap(file)) { Bitmap g = new Bitmap(o.Widt ...
- Android应用开发中半透明效果实现方案
下面是自定义Activity半透明的效果例子:res/values/styles.xml<resources> <stylename="Transparent " ...
- 突袭HTML5之SVG 2D入门1 - SVG综述////////////////zzzzzzzz
以二次贝塞尔曲线的公式为例: js函数: //p0.p1.p2三个点,其中p0为起点,p2为终点,p1为控制点 //它们的坐标用数组表示[x,y] //t的范围是0-1 function qBerzi ...
- 跨列设置column-span
column-span主要用来定义一个分列元素中的子元素能跨列多少.column-width.column-count等属性能让一元素分成多列,不管里面元素如何排放顺序,他们都是从左向右的放置内容,但 ...
- Windows Phone 二十一、联系人存储
联系人资料是手机上必有的,在最新的 Windows Phone 中开放了相应的 API ,以便于应用程序读写通讯录. 注意:系统没有对整个手机自带的通讯录写入开放权限,每个应用只能管理属于当前应用的联 ...
- 常用git命令总结
这些命令是最常用的,一般的提交代码.拉取代码.合并代码.分支切换等等操作用这些命令就足够了. 1.git init 把一个目录初始化成git仓库 2.git add test.txt 把文 ...
- WebAPI使用多个xml文件生成帮助文档
一.前言 上篇有提到在WebAPI项目内,通过在Nuget里安装(Microsoft.AspNet.WebApi.HelpPage)可以根据注释生成帮助文档,查看代码实现会发现是基于解析项目生成的xm ...
- js 简体中文拼音对应表
https://github.com/silaLi/pinyin js 拼音对象,包涵大部分文字