输入端口号后,点击启动监听
输入IP(服务器的IP地址)和端口号后,点击连接按钮,连接成功如下图所示:
//设置进度条 ui->progressBar->setRange(0,100); ui->progressBar->setValue(0); QWidget *progressWidget = new QWidget(this); progressWidget->setLayout(new QHBoxLayout()); progressWidget->layout()->addWidget(ui->progressBar); // 创建 QStatusBar // 将小部件添加到 QStatusBar ui->statusbar->addPermanentWidget(progressWidget); // 设置主窗口的状态栏 setStatusBar(ui->statusbar); ui->statusbar->setSizeGripEnabled(false); //创建线程对象 QThread *thread = new QThread; //创建任务对象 RecvFile *recvWork = new RecvFile; //将任务对象移到子线程中 recvWork->moveToThread(thread); connect(this,&MainWindow::startListen,recvWork,&RecvFile::startListen); //更新进度条 connect(recvWork,&RecvFile::curPercent,ui->progressBar,&QProgressBar::setValue); //启动线程 thread->start();
void RecvFile::startListen(unsigned short port) { qDebug()<listen(QHostAddress::Any,port); connect(tcpServer,&QTcpServer::newConnection,[=]() { //取出建立好连接的套接字 tcpSocket = tcpServer->nextPendingConnection(); isStart = true; connect(tcpSocket,&QTcpSocket::readyRead,this,&RecvFile::recvFile); connect(tcpSocket,&QTcpSocket::disconnected,this,[=]() { //断开连接 tcpSocket->close(); tcpSocket->deleteLater(); }); }); } void RecvFile:: recvFile() { qDebug()<<"触发recvFile"; //取出接收的内容 QByteArray buf = tcpSocket->readAll(); if(true == isStart)//之前未接收文件的头部信息 { //接收头部 qDebug()<<"接收头部==="; isStart = false; //解析头部 buf的内容格式 <文件名>##<文件大小> QString token=QString(buf).section("##",0,0);//token qDebug()<<"token1="<0) { recvfilesize += len;//累计接收大小 int percent = ((recvfilesize)*100)/filesize; //发出更新进度条的信号 //qDebug()<<"percent="<write(completionMessage); tcpSocket->waitForBytesWritten(); // 等待数据写入完毕 } else{ qDebug()<<"recvfilesize != filesize"; //isStart = true; } } } void RecvFile::sendDownloadFile(QString path,QString targetDir)//发送头 { timer = new QTimer(this); connect(timer,&QTimer::timeout,[=]() { //关闭定时器 timer->stop(); //发送文件数据 sendDownloadFileData(); }); file.setFileName(path); //获取文件信息 QFileInfo info(path); filesize = info.size();//获取文件大小 filename = info.fileName();//获取文件名 //============================================Token================================================================== QString token="197%*FILE*%197"; //============================================Token================================================================== //只读方式打开文件 bool isOk = file.open(QIODevice::ReadOnly); if(true == isOk) { //创建文件头信息 QString head = QString("%1##%2##%3##%4").arg(token).arg(filename).arg(filesize).arg(targetDir); //创建文件头信息,格式为"文件名##文件大小",例如 "example.txt##1024" //发送头部信息 qint64 len = tcpSocket->write(head.toUtf8()); if(len>0)//发送成功 { //防止tcp黏包问题,延时20ms timer->start(20); } else { //发送失败 file.close(); } } else { QMessageBox::warning(nullptr,"错位","打开文件失败!"); return; } }