最近看Qt 的网络编程关于Tcp传输文件的问题, (按照这个文章实现的[url]http://www.yafeilinux.com/?p=806[/url]),
但是我很郁闷的是为什么我的tcpSender中的bytesWritten(quint64)信号没有上来, 刚开始的连接都是正常的。 望高手指点。
tcpsender.cpp
#include <qfiledialog.h>
#include "tcpsender.h"
tcpSender::tcpSender(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
loadSize = 4 * 1024;
totalBytes = 0;
bytesWrittenAA = 0;
bytesToWrite = 0;
tcpClient = new QTcpSocket(this);
connect(tcpClient, SIGNAL(connected()), this, SLOT(startTransfer()));
connect(tcpClient, SIGNAL(bytesWritten(quint64)), this, SLOT(updateClientProgress(qint64)));
connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
ui.setupUi(this);
ui.sendButton->setEnabled(false);
}
tcpSender::~tcpSender()
{
}
void tcpSender::OpenFile()
{
fileName = QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty())
{
ui.sendButton->setEnabled(true);
ui.clientStatusLabel->setText(tr("打开文件 %1成功!").arg(fileName));
}
}
void tcpSender::send()
{
ui.sendButton->setEnabled(false);
bytesWrittenAA = 0;
ui.clientStatusLabel->setText(tr("连接中..."));
tcpClient->connectToHost(ui.hostLineEdit->text(), ui.portLineEdit->text().toInt());
}
void tcpSender::startTransfer()
{
localFile = new QFile(fileName);
if (!localFile->open(QFile::ReadOnly))
{
qDebug() << "open file error!";
return;
}
totalBytes = localFile->size();
QDataStream sendOut(&outBlock, QIODevice::WriteOnly);
sendOut.setVersion(QDataStream::Qt_4_6);
QString currentFileName = fileName.right(fileName.size() - fileName.lastIndexOf("/") - 1);
sendOut << qint64(0) << qint64(0) << currentFileName;
totalBytes += outBlock.size();
sendOut.device()->seek(0);
sendOut << totalBytes << qint64((outBlock.size() - sizeof(qint64) * 2));
bytesToWrite = totalBytes - tcpClient->write(outBlock);
ui.clientStatusLabel->setText(tr("已连接"));
outBlock.resize(0);
}
void tcpSender::updateClientProgress(qint64 numBytes)
{
bytesWrittenAA += numBytes;
if (bytesWrittenAA > 0)
{
outBlock = localFile->read(qMin(bytesToWrite, loadSize));
bytesToWrite -= (int)tcpClient->write(outBlock);
outBlock.resize(0);
}
else
{
localFile->close();
}
ui.clientProgressBar->setMaximum(totalBytes);
ui.clientProgressBar->setValue(bytesWrittenAA);
if (bytesWrittenAA == totalBytes)
{
ui.clientStatusLabel->setText(tr("传输文件 %1成功").arg(fileName));
localFile->close();
tcpClient->close();
}
}
void tcpSender::displayError(QAbstractSocket::SocketError)
{
qDebug() << tcpClient->errorString();
tcpClient->close();
ui.clientProgressBar->reset();
ui.clientStatusLabel->setText(tr("客户端就绪"));
ui.sendButton->setEnabled(true);
}
void tcpSender::on_openButton_clicked()
{
OpenFile();
}
void tcpSender::on_sendButton_clicked()
{
send();
}
//tcpreceiver.cpp
#include "tcpreceiver.h"