qt4 tcp QTcpSocket QTcpServer 传输文件

来源:互联网 发布:关闭 搜索合作网络 编辑:程序博客网 时间:2024/04/29 05:43
tcpSender (客户端无QTcpServer)
[cpp] view plaincopy
  1. private:  
  2.         QTcpSocket *tcpClient;  
  3.         QFile *localFile;  //要发送的文件  
  4.         qint64 totalBytes;  //数据总大小  
  5.         qint64 bytesWritten;  //已经发送数据大小  
  6.         qint64 bytesToWrite;   //剩余数据大小  
  7.         qint64 loadSize;   //每次发送数据的大小  
  8.         QString fileName;  //保存文件路径  
  9.         QByteArray outBlock;  //数据缓冲区,即存放每次要发送的数据  
  10. private slots:  
  11.     void send();  //连接服务器  
  12.     void startTransfer();  //发送文件大小等信息  
  13.     void updateClientProgress(qint64); //发送数据,更新进度条  
  14.     void displayError(QAbstractSocket::SocketError); //显示错误  
  15.     void openFile();  //打开文件  
[cpp] view plaincopy
  1. Widget::Widget(QWidget *parent) :  
  2.     QWidget(parent),  
  3.     ui(new Ui::Widget)  
  4. {  
  5.     ui->setupUi(this);  
  6.     loadSize = 4*1024;  
  7.     totalBytes = 0;  
  8.     bytesWritten = 0;  
  9.     bytesToWrite = 0;  
  10.     tcpClient = new QTcpSocket(this);  
  11.     connect(tcpClient,SIGNAL(connected()),this,SLOT(startTransfer()));  
  12.     //当连接服务器成功时,发出connected()信号,我们开始传送文件  
  13.     connect(tcpClient,SIGNAL(bytesWritten(qint64)),this,SLOT(updateClientProgress(qint64)));  
  14.     //当有数据发送成功时,我们更新进度条  
  15.     connect(tcpClient,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));  
  16.     ui->sendButton->setEnabled(false);  
  17.     ui->hostLineEdit->setText("192.168.1.100");  
  18.     ui->portLineEdit->setText("6666");  
  19. }  
[cpp] view plaincopy
  1. void Widget::openFile()   //打开文件  
  2. {  
  3.     fileName = QFileDialog::getOpenFileName(this);  
  4.     if(!fileName.isEmpty())  
  5.     {  
  6.         ui->sendButton->setEnabled(true);  
  7.         ui->clientStatusLabel->setText(tr("打开文件 %1 成功!").arg(fileName));  
  8.     }  
  9. }  
  10.   
  11.   
  12. void Widget::send()   //连接到服务器,执行发送  
  13. {  
  14.     ui->sendButton->setEnabled(false);  
  15.     bytesWritten = 0;  
  16.     //初始化已发送字节为0  
  17.     ui->clientStatusLabel->setText(tr("连接中…"));  
  18.     tcpClient->connectToHost(QHostAddress(ui->hostLineEdit->text()),ui->portLineEdit->text().toInt());//连接  
  19. }  
  20.   
  21. void Widget::on_openButton_clicked() //打开按钮  
  22. {  
  23.     openFile();  
  24. }  
  25.   
  26. void Widget::on_sendButton_clicked() //发送按钮  
  27. {  
  28.     send();  
  29. }  

[cpp] view plaincopy
  1. void Widget::startTransfer()  //实现文件大小等信息的发送  
  2. {  
  3.     localFile = new QFile(fileName);  
  4.     if(!localFile->open(QFile::ReadOnly))  
  5.     {  
  6.         qDebug() << "open file error!";  
  7.         return;  
  8.     }  
  9.     totalBytes = localFile->size();  
  10.     //文件总大小  
  11.     QDataStream sendOut(&outBlock,QIODevice::WriteOnly);  
  12.     sendOut.setVersion(QDataStream::Qt_4_6);  
  13.     QString currentFileName = fileName.right(fileName.size() - fileName.lastIndexOf('/')-1);  
  14.     sendOut << qint64(0) << qint64(0) << currentFileName;  
  15.     //依次写入总大小信息空间,文件名大小信息空间,文件名---仅是文件名不含路径,没必要含路径  
  16.     totalBytes += outBlock.size();  
  17.     //这里的总大小是文件名大小等信息和实际文件大小的总和  
  18.     sendOut.device()->seek(0);  
  19.     sendOut<<totalBytes<<qint64((outBlock.size() - sizeof(qint64)*2));  
  20.     //totalBytes是文件总大小,即两个quint64的大小+文件名+文件实际内容的大小  
  21.     //qint64((outBlock.size() - sizeof(qint64)*2))得到的是文件名大小  
  22.     bytesToWrite = totalBytes - tcpClient->write(outBlock);  
  23.     //发送完头数据后剩余数据的大小,即文件实际内容的大小  
  24.     ui->clientStatusLabel->setText(tr("已连接"));  
  25.     outBlock.resize(0);  
  26. }  

[cpp] view plaincopy
  1. void Widget::updateClientProgress(qint64 numBytes) //更新进度条,实现文件的传送  
  2. {  
  3.     bytesWritten += (int)numBytes;  
  4.     //已经发送数据的大小  
  5.     if(bytesToWrite > 0) //如果已经发送了数据  
  6.     {  
  7.         outBlock = localFile->read(qMin(bytesToWrite,loadSize));  
  8.       //每次发送loadSize大小的数据,这里设置为4KB,如果剩余的数据不足4KB,  
  9.       //就发送剩余数据的大小  
  10.         bytesToWrite -= (int)tcpClient->write(outBlock);  
  11.        //发送完一次数据后还剩余数据的大小  
  12.         outBlock.resize(0);  
  13.        //清空发送缓冲区  
  14.     }  
  15.     else  
  16.     {  
  17.         localFile->close(); //如果没有发送任何数据,则关闭文件  
  18.     }  
  19.     ui->clientProgressBar->setMaximum(totalBytes);  
  20.     ui->clientProgressBar->setValue(bytesWritten);  
  21.     //更新进度条  
  22.     if(bytesWritten == totalBytes) //发送完毕  
  23.     {  
  24.         ui->clientStatusLabel->setText(tr("传送文件 %1 成功").arg(fileName));  
  25.         localFile->close();  
  26.         tcpClient->close();  
  27.     }  
  28. }  

[cpp] view plaincopy
  1. void Widget::displayError(QAbstractSocket::SocketError) //显示错误  
  2. {  
  3.     qDebug() << tcpClient->errorString();  
  4.     tcpClient->close();  
  5.     ui->clientProgressBar->reset();  
  6.     ui->clientStatusLabel->setText(tr("客户端就绪"));  
  7.     ui->sendButton->setEnabled(true);  
  8. }  

流程:
1创建tcpSocket ,tcpClient= new QTcpSocket(this);
2.关联信号connected和槽函数startTransfer,connect(tcpClient,SIGNAL(connected()),this,SLOT(startTransfer()));其中信号connected在连接服务器成功(即本客户端执行 tcpClient->connectToHost,得到服务器的成功响应)时发射,此时执行startTransfer开始传输文件头数据
3.关联信号bytesWritten和槽函数updateClientProgress,connect(tcpClient,SIGNAL(bytesWritten(qint64)),this,SLOT(updateClientProgress(qint64)));其中信号bytesWritten在当有数据发送成功时(即本客户端执行 tcpClient->write(outBlock);服务器的成功收outBlock时)时发射,此时执行updateClientProgress来更新进度条并接着发送剩余数据
4.连接到某个ip的某个端口,tcpClient->connectToHost(QHostAddress(ui->hostLineEdit->text()),ui->portLineEdit->text().toInt())
5.实现槽函数startTransfer,开始传输文件头数据
5.实现槽函数updateClientProgress,更新进度条,并接着发送剩余数据
其中发送的文件头包括一个quint64(记录文件总大小,包括sizeof(quint64)+sizeof(quint64)+文件名+文件实际内容),一个quint64(记录文件名大小),一个文件名不含路径,一个文件实际内容


tcpReceiver
[cpp] view plaincopy
  1. private:  
  2.         QTcpServer tcpServer;  
  3.         QTcpSocket *tcpServerConnection;  
  4.         qint64 totalBytes;  //存放总大小信息  
  5.         qint64 bytesReceived;  //已收到数据的大小  
  6.         qint64 fileNameSize;  //文件名的大小信息  
  7.         QString fileName;   //存放文件名  
  8.         QFile *localFile;   //本地文件  
  9.         QByteArray inBlock;   //数据缓冲区  
  10. private slots:  
  11.     void start();   //开始监听  
  12.     void acceptConnection();  //建立连接  
  13.     void updateServerProgress();  //更新进度条,接收数据  
  14.     void displayError(QAbstractSocket::SocketError socketError);  

[cpp] view plaincopy
  1. Widget::Widget(QWidget *parent) :  
  2.     QWidget(parent),  
  3.     ui(new Ui::Widget)  
  4. {  
  5.     ui->setupUi(this);  
  6.         totalBytes = 0;  
  7.         bytesReceived = 0;  
  8.         fileNameSize = 0;  
  9.         connect(&tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));  
  10.     //当发现新连接时发出newConnection()信号  
  11. }  
[cpp] view plaincopy
  1. void Widget::start() //开始监听  
  2. {  
  3.     ui->startButton->setEnabled(false);  
  4.     bytesReceived =0;  
  5.     if(!tcpServer.listen(QHostAddress("192.168.1.100"),6666))  
  6.     {  
  7.         qDebug() << tcpServer.errorString();  
  8.         close();  
  9.         return;  
  10.     }  
  11.     ui->serverStatusLabel->setText(tr("监听"));  
  12. }  
  13.   
  14. void Widget::on_startButton_clicked() //开始监听按钮  
  15. {  
  16.     start();  
  17. }  

[cpp] view plaincopy
  1. void Widget::acceptConnection()  //接受连接  
  2. {  
  3.     tcpServerConnection = tcpServer.nextPendingConnection();  
  4.     connect(tcpServerConnection,SIGNAL(readyRead()),this,SLOT(updateServerProgress()));  
  5.     connect(tcpServerConnection,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));  
  6.     ui->serverStatusLabel->setText(tr("接受连接"));  
  7.     tcpServer.close();  
  8. }  

[cpp] view plaincopy
  1. void Widget::updateServerProgress()  //更新进度条,接收数据  
  2. {  
  3.     QDataStream in(tcpServerConnection);  
  4.     in.setVersion(QDataStream::Qt_4_6);  
  5.   
  6.     if(bytesReceived <= sizeof(qint64)*2)  
  7.     { //如果接收到的数据小于16个字节,那么是刚开始接收数据,我们保存到//来的头文件信息  
  8.   
  9.         if((tcpServerConnection->bytesAvailable() >= sizeof(qint64)*2)&& (fileNameSize == 0))  
  10.         { //接收数据总大小信息和文件名大小信息  
  11.             in >> totalBytes >> fileNameSize;  
  12.             bytesReceived += sizeof(qint64) * 2;  
  13.         }  
  14.   
  15.         if((tcpServerConnection->bytesAvailable() >= fileNameSize)  
  16.                 && (fileNameSize != 0))  
  17.         {  //接收文件名,并建立文件  
  18.             in >> fileName;  
  19.             ui->serverStatusLabel->setText(tr("接收文件 %1 …").arg(fileName));  
  20.             bytesReceived += fileNameSize;  
  21.             localFile = new QFile(fileName);  
  22.             if(!localFile->open(QFile::WriteOnly))  
  23.             {  
  24.                 qDebug() << "open file error!";  
  25.                 return;  
  26.             }  
  27.         }  
  28.   
  29.         else return;  
  30.     }  
  31.   
  32.   
  33.     if(bytesReceived < totalBytes)  
  34.     {  //如果接收的数据小于总数据,那么写入文件  
  35.         bytesReceived += tcpServerConnection->bytesAvailable();  
  36.         inBlock = tcpServerConnection->readAll();  
  37.         localFile->write(inBlock);  
  38.         inBlock.resize(0);  
  39.     }  
  40.   
  41.     ui->serverProgressBar->setMaximum(totalBytes);  
  42.     ui->serverProgressBar->setValue(bytesReceived);  
  43.     //更新进度条  
  44.     if(bytesReceived == totalBytes)  
  45.   
  46.     { //接收数据完成时  
  47.         tcpServerConnection->close();  
  48.         localFile->close();  
  49.         ui->startButton->setEnabled(true);  
  50.         ui->serverStatusLabel->setText(tr("接收文件 %1 成功!").arg(fileName));  
  51.     }  
  52. }  

[cpp] view plaincopy
  1. void Widget::displayError(QAbstractSocket::SocketError) //错误处理  
  2. {  
  3.     qDebug() << tcpServerConnection->errorString();  
  4.     tcpServerConnection->close();  
  5.     ui->serverProgressBar->reset();  
  6.     ui->serverStatusLabel->setText(tr("服务端就绪"));  
  7.     ui->startButton->setEnabled(true);  
  8. }  

流程
1.创建 QTcpServer tcpServer;使之监听本机的某个端口,tcpServer.listen(QHostAddress("192.168.1.100"),6666)
2,关联信号newConnection和槽函数sendMessage, connect(&tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));其中信号newConnection在有客户端的连接请求(即客户端执行tcpSocket->connectToHost)时发射,此时执行acceptConnection
3.实现槽函数acceptConnection,在里面
从tcpServer取得已经建立但挂起的QTcpSocket连接
tcpServerConnection = tcpServer.nextPendingConnection();
并关联信号readyRead和槽函数updateServerProgress,
connect(tcpServerConnection,SIGNAL(readyRead()),this,SLOT(updateServerProgress()));其中信号readyRead在有新的数据到达时发射,此时执行updateServerProgress函数把接收到的数据保存到文件,并更新进度条
4.实现槽函数updateServerProgress

从上篇和此篇可看出基于客户和服务器的tcp编程:
需要在服务器端有QTcpServer监视某个端口,在客户端使用QTcpSocket发起连接,然后在服务器端获取连接QTcpSocket,然后双方就使用QTcpSocket提供的方法来互发数据其中,
发送方使用 QByteArray block; clientConnection->write(block);发送数据,使用bytesWritten信号得知数据已经发送完成
接收方使用readyRead信号得知有数据到达,使用  QDataStream in(tcpSocket); in >> message;
0 0
原创粉丝点击