void Client::newConn() { blockSize = 0; tClnt->abort(); tClnt->connectToHost(hostAddr, tPort); time.start();//建立好连接后便开始计时 } void Client::readMsg() { QDataStream in(tClnt); in.setVersion(QDataStream::Qt_4_7); float useTime = time.elapsed(); if (bytesReceived <= sizeof(qint64)2){ if((tClnt->bytesAvailable() >= sizeof(qint64)2) && (fileNameSize == 0)) { in >> totalBytes >>fileNameSize; bytesReceived += sizeof(qint64)2; } if((tClnt->bytesAvailable() >= fileNameSize) && (fileNameSize != 0)){ in>>fileName; bytesReceived += fileNameSize; if (!locFile->open(QFile::WriteOnly)){ QMessageBox::warning(this, tr("应 用 程 序"), tr("无法读取文件 %1:\n%2.") .arg(fileName).arg(locFile->errorString())); return; } }else { return; } } if (bytesReceived < totalBytes) { bytesReceived += tClnt->bytesAvailable(); inBlock = tClnt->readAll(); locFile->write(inBlock); inBlock.resize(0); } ui->progressBar->setMaximum(totalBytes); ui->progressBar->setValue(bytesReceived); double speed = bytesReceived / useTime; ui->cStatusLbl->setText(tr("已接收 %1MB (%2MB/s) \n 共%3MB 已用时:%4" "秒\n估计剩余时间:%5秒") .arg(bytesReceived / (10241024)) .arg(speed1000/(10241024), 0, 'f',2) .arg(totalBytes / (1024 * 1024)) .arg(useTime/1000, 0, 'f', 0) .arg(totalBytes/speed/1000 - useTime/1000, 0, 'f', 0)); if(bytesReceived == totalBytes) { locFile->close(); tClnt->close(); ui->cStatusLbl->setText(tr("接收文件 %1 完毕").arg(fileName)); } }
时间: 2024-04-02 09:32:06 浏览: 67
http-2:HTTP2协议的纯Ruby实现
这段代码是关于网络文件下载的,实现了客户端从服务器下载文件并显示下载进度和速度等信息。函数`newConn()`是用于建立连接的,函数`readMsg()`是用于读取文件内容的。其中,`tClnt`是QTcpSocket类型的指针,用于和服务器建立连接和读取数据;`in`是QDataStream类型的对象,用于读取数据;`locFile`是QFile类型的指针,用于保存下载的文件到本地;`totalBytes`和`bytesReceived`是用于记录下载进度的变量;`fileNameSize`和`fileName`是用于记录下载文件的名称和大小的变量;`useTime`和`speed`是用于记录下载所用时间和下载速度的变量。
阅读全文