DOC

QDataStream

By Theresa Ross,2014-03-25 09:14
13 views 0
QDataStream

学过Qt的前辈帮个忙

    楼主weilong122;萧瑟;2006-05-26 22:36:34 Linux/Unix社区 / 程序开发区 提问

    我在用Qt做文件传输的时候发生了一个情况

     当我发送一个文本文件的时候?在接收方接到的是文本文件的一部分?这一部分重复接收

     求高手给点建议

     ============================================================================

     发送端

     void Sender::ConnectTo() //与接收端取得连接

     {

     tcpSocket = new QTcpSocket(this);

     tcpSocket->connectToHost(Ipedit->text(),5002);

     connect(tcpSocket, SIGNAL(connected ()), this, SLOT(SendFile()));

     }

     void Sender::SendFile()//向接收端发送文件

     {

     int bytesWrite = 0;

     fileName = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath());

     QFile Sendfile(fileName);

     Sendfile.open(QIODevice::ReadOnly);

     QDataStream stream( tcpSocket );

     QFileInfo f(fileName);

     fileName = f.fileName();

     int filesize =f.size();

     stream << filesize;

     stream << fileName;

     while(!Sendfile.atEnd())

     {

     if(bytesWrite + 2048 <= filesize)

     {

     char buf[2048];

     Sendfile.read(buf, 2048);

     stream.writeRawData(buf,2048);

     bytesWrite += 2048;

     }

     else{

     int blocksize = filesize - bytesWrite;

     char buf[blocksize];

     Sendfile.read(buf, blocksize);

     stream.writeRawData(buf,blocksize);

     }

     }

     Sendfile.close();

     }

     ========================================================================

     接收端

     void Sender::AcceptConnection()//接收发送方的连接

     {

     clientConnection = tcpServer->nextPendingConnection();

     connect(clientConnection, SIGNAL(readyRead()),this,SLOT(ReceiveFile()));

     showEdit->append("connection");

     }

     void Sender::ReceiveFile() //接收文件

     {

     int filesize = 0;

     int readsize = 0;

     QDataStream in(clientConnection);

     in >> filesize;

     in >> fileName;

     QFile file(fileName);

     if (!file.open(QFile::WriteOnly | QFile::Append))

     {

     QMessageBox::warning(this,"error","can not open the file!");

     return;

     }

     while (1)

     {

     if( clientConnection->isReadable())

     {

     if(readsize + 2048 <= filesize)

     {

     buf = new char[2048];

     clientConnection->read(buf, 2048);

     file.write(buf, 2048);

     readsize += 2048;

     delete []buf;

     if(readsize == filesize) break;

     }

     else

     {

     int blocksize = filesize - readsize;

     buf = new char[blocksize];

     clientConnection->read(buf, blocksize);

     file.write(buf, blocksize);

     readsize += blocksize;

     delete []buf;

     if(readsize == filesize) break;

     }

     }

     }

     file.close();

     clientConnection->disconnect();

     }

Report this document

For any questions or suggestions please email
cust-service@docsford.com