注意:工程监理后,因为用到网路,所以要加入对应的库

服务器:

.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传送文件的更多相关文章

  1. 读书笔记——《图解TCP/IP》(1/4)

    读书笔记——<图解TCP/IP>(1/4) 经典摘抄 第一章 网络基础知识 1.独立模式:计算机未连接到网络,各自独立使用的方式. 2.广域网 WAN 局域网 LAN 城域网 MAN 3. ...

  2. SZ,RZ传送文件

    linux 和window之间通过xshell的命令 SZ,RZ传送文件:

  3. python使用简单http协议来传送文件

    python使用简单http协议来传送文件!在ubuntu环境下,局域网内可以使用nc来传送文件,也可以使用基于Http协议的方式来下载文件我们可以使用python -m SimpleHTTPServ ...

  4. QT运行时加载UI文件

      写QT程序里运行时加载UI文件,代码如下: 点击(此处)折叠或打开 #include "keyboard.h" #include <QtUiTools> #incl ...

  5. Linux SSH 远程操作与传送文件

    操作系统:centos 6.5 x64 一.远程连接:在进行linux 的 ssh远程操作前,一定要确认linux 是否安装了 openssh-clients,为了方便起见,一般用yum安装即可:# ...

  6. 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 ...

  7. Delphi IdTCPClient IdTCPServer 点对点传送文件

    https://blog.csdn.net/luojianfeng/article/details/53959175 2016年12月31日 23:40:15 阅读数:2295 Delphi     ...

  8. InstallShield 2015 LimitedEdition VS2012 运行bat文件

    转载:http://www.cnblogs.com/fengwenit/p/4271150.html  运行bat文件 网上很多介绍如何运行bat的方法,但我这个是limted 版本,不适用. 1. ...

  9. Qt SD卡 文件系统挂载、文件预览

    /********************************************************************************** * Qt SD卡 文件系统挂载. ...

随机推荐

  1. golang DynamoDB sdk AccessDeniedException

    golang调用aws sdk时候提示: AccessDeniedException: User: arn:aws:sts::818539432014:assumed-role/bj-develop/ ...

  2. 只需三步--轻松反编译Android Apk文件

    安卓程序是通过java语言进行编写的,可以很容易进行反编译.很多apk文件被反编译后再二次打包,就成了自己的产品,很是流氓.下面我们来看看如何进行apk的反编译,以及常用的防反编译手段. 一.反编译A ...

  3. vulcan测试记录

    感觉这个游戏很赞,是六个里面最喜欢的一个了 1.有时候挖坑对于位置要求比较大? 2.感觉难度比较大,尤其是玩到第三关很考验啊(不过从另一个方面来说也是优点?) 3.玩到现在对于怪物吃金子的原理没有很懂 ...

  4. New line

    The concepts of line feed (LF) and carriage return (CR) are closely associated, and can be either co ...

  5. cs

    cs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o ...

  6. PHP部分资料

    完善PHP登陆注册页面,同时连接mysql数据库 http://blog.csdn.net/tianlu1677/article/details/7765889/ PHP 附录 : 用户注册与登录完整 ...

  7. mac上启动Java项目失败

    解决办法参考地址:http://bbs.csdn.net/topics/390813742,感谢csdn账号为iwordword的大神

  8. SQL用先进先出存储过程求出库数量

    create table t( id ,), name ),--商品名称 j int, --入库数量 c int, --出库数量 jdate datetime --入库时间 ) ,,'2007-12- ...

  9. 【转帖】ActiveX部件不能创建对象的终极解决方案

    建一个批处理文件,内容如下: echo 正在修复,这个过程可能需要几分钟,请稍候-- rundll32.exe advpack.dll /DelNodeRunDLL32 %systemroot%Sys ...

  10. Java类的基本运行顺序是怎样

    我们以下面的类来说明一个基本的 Java 类的运行顺序: public class Demo{ private String name; private int age; public Demo(){ ...