QtTCP大型实验源代码
qt实例100例代码

qt实例100例代码摘要:1.项目背景及意义2.QT简介3.实例100例代码概述4.实例分类与代码解析5.总结与拓展正文:一、项目背景及意义随着科技的不断发展,嵌入式系统在各行各业中的应用越来越广泛。
作为一种跨平台的C++图形用户界面应用程序开发框架,Qt在嵌入式领域具有很高的地位。
本文旨在为广大开发者提供一个实用的Qt实例教程,帮助大家更好地掌握Qt编程技巧,为嵌入式项目开发提供支持。
二、QT简介Qt是一款由挪威公司Trolltech创立的跨平台C++图形用户界面(GUI)应用程序开发框架。
Qt具有以下特点:1.基于C++:Qt使用C++作为编程语言,具有良好的性能和可移植性。
2.跨平台:Qt支持多种操作系统,如Windows、Linux、macOS等。
3.强大的组件库:Qt提供了丰富的图形界面组件,方便开发者快速搭建应用程序。
4.良好的集成开发环境(IDE):Qt提供了一套完整的开发工具,包括QtCreator、Qt Designer等。
5.面向对象:Qt遵循面向对象编程(OOP)原则,有助于提高代码的可维护性和可重用性。
三、实例100例代码概述本文将介绍Qt实例100例代码,这些实例涵盖了Qt的各个方面,包括基本组件、布局管理、网络通信、数据库操作、多媒体、绘图等。
通过学习这些实例,读者可以逐步掌握Qt的应用技巧,为自己的项目打下坚实基础。
四、实例分类与代码解析1.基本组件:包括QWidget、QLabel、QPushButton、QVBoxLayout 等基本组件的使用。
2.布局管理:介绍Qt的布局管理器,如QBoxLayout、QGridLayout、QFormLayout等。
3.网络通信:涉及TCP/IP、UDP协议的使用,以及QTcpServer、QTcpClient等类的作用。
4.数据库操作:介绍如何使用Qt进行数据库查询、插入、更新和删除等操作。
5.多媒体:包括音频、视频播放,以及图像处理等。
qtcpsocket案例

qtcpsocket案例QTcpSocket是Qt框架提供的用于进行TCP通信的类。
它提供了一系列的接口函数,可以实现TCP客户端和服务器端的功能。
下面是一个使用QTcpSocket的案例。
假设我们有一个简单的网络聊天室系统,实现客户端之间的聊天功能。
首先我们需要创建一个客户端,连接到服务器。
客户端发送消息给服务器,当服务器接收到消息后,将消息广播给所有连接到服务器的客户端。
首先创建一个Qt的控制台应用程序,包括头文件`QTcpSocket`。
在主函数中创建一个客户端类`ChatClient`,并调用其成员函数`start`启动客户端。
```cpp#include <QCoreApplication>#include <QTcpSocket>class ChatClient : public QObjectQ_OBJECTpublic:ChatClientsocket = new QTcpSocket(this);connect(socket, &QTcpSocket::connected, this,&ChatClient::onConnected);connect(socket, &QTcpSocket::readyRead, this,&ChatClient::onReadyRead);}void startsocket->connectToHost("localhost", 1234);qDebug( << "Connecting to server...";}private slots:void onConnectedqDebug( << "Connected to server";socket->write("Hello server");}void onReadyReadQString message = QString::fromUtf8(socket->readAll();qDebug( << "Received message:" << message;}private:QTcpSocket* socket;};int main(int argc, char *argv[])QCoreApplication a(argc, argv);ChatClient client;client.start(;return a.exec(;```上面的代码中,我们首先在构造函数中创建了一个`QTcpSocket`对象,并连接了`connected`和`readyRead`信号,分别与`onConnected`和`onReadyRead`槽函数绑定。
qt qtcpsocket 用法

qt qtcpsocket 用法QT是一种跨平台开发工具,支持多种编程语言,例如C++、Java 等,QT拥有强制性的C++ API,允许开发者完成各种应用程序的UI设计、数据库操作、网络编程等功能。
QT中的QTcpSocket是一个可以用于网络通信的类,它提供了一个TCP套接字便捷的封装,允许开发者以同步或异步方式将数据从客户端发送到服务器。
下面,我们来一步步阐述QT的QTcpSocket的用法。
第一步:使用QTcpSocket建立连接我们可以使用下面的代码来使用QTcpSocket建立连接:```cppQTcpSocket socket;socket.connectToHost(hostName, portNumber);if(socket.waitForConnected())qDebug() << "Connected to host " << hostName << " on port " << portNumber;elseqDebug() << "Connection failed.";```其中,hostName和portNumber分别是我们需要连接的主机名和端口号。
可以通过waitForConnected函数来等待连接成功。
连接成功后,调试器将输出Connected to host xxx on port yyy。
第二步:发送数据成功建立连接后,我们可以使用QTcpSocket发送数据,以发送字符串为例:```cppQString message = "Hello, world!";socket.write(message.toUtf8());```这里,我们首先将要发送的字符串转换为UTF-8编码格式,并调用QTcpSocket的write函数发送数据。
QT_TCP下的socket编程

QT TCP下的socket编程转载:/blog/static/1755423992011215641 781/qt_转载 2011-03-01 17:06:41 阅读8 评论0 字号:大中小订阅QTcpSocket 和 QTcpServer类实现了Qt的Tcp客户端和服务器。
tcp是一个流式协议。
对于应用程序来说,数据是一个很长的流,有点像一个巨大的文件。
搞成此的协议建立在面向块的tcp协议(Block-oriented)或面向行(Line-oriented )的tcp协议上。
面向块的tcp协议,数据被当作一个2进制的块来传输。
没每一个块被当作一个定义了大小的,后面跟随了数据的字段。
面向行的tcp协议,数据被当作一个文本文件的一行。
一个传输终止于一个新的行的到来。
QTcpSocket 继承自 QIODevice,所以它可以从 QDataStream 或 QTextStream 中读取或写入数据。
从文件读数据和从网络上读数据有一个明显的不同点:我们必须保证用“>> ”操作符读取数据时,已经从另一方接收了足够的数据。
如果你这样做了,那么一个失败的结果是:行为未定义。
我们来看一个使用block-oriented tcp协议的服务器和客户端的代码。
用户填写行程的起始地,目的地,日期等,服务器返回符合要求的行程。
界面用QDesigner设计的。
叫做“tripplanner.ui”。
请使用uic工具转换。
include "ui_tripplanner.h"class TripPlanner : public QDialog, public Ui::TripPlanner{Q_OBJECTpublic:TripPlanner(QWidget *parent = 0);private slots:void connectToServer();void sendRequest();void updateTableWidget();void stopSearch();void connectionClosedByServer();void error();private:void closeConnection();QTcpSocket tcpSocket; //tcpSocket变量是QTcpSocket 类型,用来建立一个tcp连接。
QT中TCP通信及遇到的问题

QT中TCP通信及遇到的问题以⾃定数据包格式进⾏通信数据包格式如下:服务端代码如下:。
cpp⽂件:主界⾯程序会发送emit sendTime()和emit sendOCRMsg(OCRMsg, dateTime)信号对应HeratPack和sendData槽函数#include "TCPthread.h"#include <qdebug.h>#include <qtimer.h>#include <qthread.h>#include <qdatastream.h>TCPthread::TCPthread(QObject *parent){qDebug() << "TCPthread线程id:" << QThread::currentThread();tcpServer = NULL;//监听套接字,指定⽗对象,让其⾃动回收空间tcpServer = new QTcpServer(this);tcpServer->listen(QHostAddress::AnyIPv4, 8888);//当有客服端连接时connect(tcpServer, &QTcpServer::newConnection,this,&TCPthread::createSocket);//-----------------------------------------------------------------------------------------------}void TCPthread::createSocket() {//取出建⽴好连接的套接字QTcpSocket *tcpSocket = tcpServer->nextPendingConnection();socketList.push_back(tcpSocket);//获取客户端的IP和端⼝QString ip = tcpSocket->peerAddress().toString();qint16 port = tcpSocket->peerPort();IPort = QString("TCPClient-[%1:%2]:成功连接").arg(ip).arg(port);qDebug() << IPort;connect(tcpSocket, &QTcpSocket::connected,[=]() {qDebug() << "成功和服务器建⽴好连接";});//接受客服端的数据connect(tcpSocket, &QTcpSocket::readyRead,this, &TCPthread::readData);//当客户端断开连接connect(tcpSocket, &QTcpSocket::disconnected, this, &TCPthread::clientDiscon);}//从客户端读取数据void TCPthread::readData() {//从通信套接字中取出内容if (socketList.size() != 0) {for (int i = 0; i < socketList.size(); i++){QByteArray array = socketList[i]->readAll();}}}//客户端断开连接void TCPthread::clientDiscon() {//与服务器连接的客户端QTcpSocket *tcpsocket = qobject_cast<QTcpSocket*>(QObject::sender());//移除socketList.removeOne(tcpsocket);qDebug() << "Client-IP:" << tcpsocket->peerAddress().toString() << "断开连接";tcpsocket->deleteLater();}//TCP服务器发送板坯报⽂数据槽函数void TCPthread::sendData(QString OCR_Msg, QDateTime dateTime) {//封装包头QByteArray sendOCRByte;//⽤于发送数据的字节数组QDataStream out(&sendOCRByte, QIODevice::WriteOnly);//使⽤数据流写⼊数据out.setByteOrder(QDataStream::LittleEndian);//设置⼩端模式out << ushort(0) << m_OCRPackID;//占位符,这⾥必须要先这样占位,然后后续读算出整体长度后在插⼊qDebug() << "报⽂头长度:" << sendOCRByte.length();//4//封装数据QString s_data = OCR_Msg + dateTime.toString("yyyy-MM-dd hh:mm:ss.zzz") +"0";qDebug() << s_data << "字符串长度:" << s_data.length();//48QByteArray ba = s_data.toLocal8Bit(); //字符串转字节数组qDebug() << "字符字节数组长度:" << ba.length(); //48//---------------------------------------------------------char * c_data;c_data = ba.data();sendOCRByte.append(c_data);//在4个字节数组中添加48个字符串//---------------------------------------------------------out.device()->seek(0);//回到数据流开头,插⼊数据的长度ushort t_len = (ushort)(sendOCRByte.length());out << t_len;qDebug() << "板坯报⽂长度:" << t_len;//52//发送数据|多例if (socketList.size() != 0) {for (int i = 0; i < socketList.size(); i++){socketList[i]->write(sendOCRByte);socketList[i]->flush();}}}//发送⼼跳报⽂void TCPthread::HeratPack() {if (socketList.size() != 0) {for (int i = 0; i < socketList.size(); i++){//⽤于⼼跳报⽂要发送的数据QByteArray sendHeartByte;//使⽤数据流写⼊数据QDataStream out(&sendHeartByte, QIODevice::WriteOnly);//设置⼩端模式out.setByteOrder(QDataStream::LittleEndian);//占位符,这⾥必须要先这样占位,然后后续读算出整体长度后在插⼊out << ushort(0) << m_heartPackID ;//回到⽂件开头,插⼊数据的长度out.device()->seek(0);ushort len = (ushort)(sendHeartByte.size());out << len;//4qDebug() <<"⼼跳报⽂长度:" << len << "⼼跳报⽂ID:" << m_heartPackID;//往套接字缓存中写⼊数据,并发送socketList[i]->write(sendHeartByte);socketList[i]->flush();}}}TCPthread::~TCPthread(){//主动和客户端断开连接if (socketList.size() != 0) {for (int i = 0; i < socketList.size(); i++){socketList[i]->disconnectFromHost();socketList[i]->close();socketList[i] = NULL;delete socketList[i];}}delete tcpServer;}遇到的问题:1、⼼跳报⽂中为发送4个字节长度报⽂:两个quint16类型的数据均占2个字节,甲⽅并要求使⽤⼩端模式解决办法:使⽤QByteArray字节数组进⾏写⼊2、数据报⽂中,需使⽤ushort类型2个占4个字节和48个字节字符串共52个字节解决办法:前⾯ushort类型使⽤QDataStraem类型写到QByteArray中。
qt的tcp通信编程

qt的tcp通信编程
Qt是一款跨平台的C++应用程序框架,提供了丰富的类库和工具,可以用于开发各种类型的应用程序,包括网络应用程序。
Qt的网络
模块提供了一种简单易用的TCP/IP通信编程接口,使得用户可以轻
松地开发网络应用程序。
在Qt中进行TCP通信编程,需要涉及到各种网络相关的类,例
如QTcpSocket、QTcpServer、QHostAddress等。
其中,QTcpSocket
是最常用的网络对象,它可以作为客户端和服务器端的通信对象,用于建立TCP连接、发送数据和接收数据等操作。
QTcpServer则用于
创建服务器端,负责接收客户端的连接请求,当有客户端连接成功后,它会创建一个QTcpSocket对象,用于与客户端进行通信。
为了进行TCP通信,在Qt中需要先建立TCP连接。
这可以通过QTcpSocket的connectToHost()函数实现,该函数需要指定目标主机的IP地址和端口号。
一旦连接建立成功,就可以使用QTcpSocket的write()函数向对方发送数据,同时使用readyRead()信号和read()
函数来接收对方发送的数据。
除了QTcpSocket和QTcpServer,Qt还提供了其他一些类来实现TCP通信,例如QUdpSocket、QSslSocket等。
无论使用哪种类,Qt
的网络模块都提供了一种简单易用的TCP/IP通信编程接口,使得用
户可以快速开发网络应用程序。
- 1 -。
qt qtcpsocket 用法

qt qtcpsocket 用法Qt是一种跨平台的C++应用程序开发框架,它提供了许多功能强大的类库和工具,可以帮助开发者快速构建高质量的应用程序。
其中,Qt的网络模块提供了一系列的类和函数,用于实现网络通信功能。
其中,QTcpSocket是Qt网络模块中的一个重要类,它提供了TCP 协议的客户端实现。
QTcpSocket类的使用非常简单,只需要创建一个QTcpSocket对象,然后调用connectToHost()函数连接到服务器即可。
连接成功后,可以使用write()函数向服务器发送数据,使用read()函数读取服务器返回的数据。
当然,在使用QTcpSocket类时,还需要处理一些错误和异常情况,例如连接失败、数据读取超时等。
下面是一个简单的QTcpSocket示例程序:```cpp#include <QtNetwork/QTcpSocket>#include <QCoreApplication>int main(int argc, char *argv[]){QCoreApplication a(argc, argv);QTcpSocket socket;socket.connectToHost("127.0.0.1", 1234);if (socket.waitForConnected()) {socket.write("Hello, world!");if (socket.waitForReadyRead()) {QByteArray data = socket.readAll();qDebug() << "Received data:" << data;} else {qDebug() << "Read data timeout!";}} else {qDebug() << "Connect to server failed!";}return a.exec();}```在这个示例程序中,我们创建了一个QTcpSocket对象,并使用connectToHost()函数连接到本地IP地址为127.0.0.1,端口号为1234的服务器。
qnetworkreply 例程

qnetworkreply 例程`QNetworkReply` 是Qt 框架中的一个类,它提供了对网络操作的抽象,例如GET 和POST 请求。
在Qt 中,`QNetworkReply` 是一个常用的类,用于处理网络请求和响应。
以下是一个使用`QNetworkReply` 的简单例程,该例程向一个HTTP 服务器发送一个GET 请求,并处理服务器返回的响应:```cpp#include <QCoreApplication>#include <QNetworkAccessManager>#include <QNetworkRequest>#include <QNetworkReply>#include <QDebug>int main(int argc, char *argv[]){QCoreApplication a(argc, argv);QNetworkAccessManager manager;QNetworkRequest request;// 设置请求的URLrequest.setUrl(QUrl("输入网址"));// 发送GET 请求QNetworkReply *reply = manager.get(request);// 连接信号槽,处理响应connect(reply, &QNetworkReply::finished, [&]() { if (reply->error() == QNetworkReply::NoError) { // 成功情况下,处理数据QByteArray data = reply->readAll();qDebug() << "Response:" << data;} else {// 处理错误qDebug() << "Error:" << reply->errorString();}// 删除网络回复对象reply->deleteLater();});return a.exec();}```在这个例程中,我们首先包含了必要的头文件,然后创建了一个`QNetworkAccessManager` 实例和一个`QNetworkRequest` 对象。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
客户端:#Client.proQT+=core guiQT+=networkgreaterThan(QT_MAJOR_VERSION,4):QT+=widgetsTARGET=ClientTEMPLATE=appSOURCES+=main.cpp\mainwindow.cpp\Client.cppHEADERS+=mainwindow.h\Client.hFORMS+=mainwindow.ui//Client.h#ifndef CLIENT_H#define CLIENT_H#include<QAbstractSocket>#include<QTcpSocket>class Client:public QTcpSocket//QAbstractSocket{Q_OBJECTpublic:explicit Client(QObject*parent=0);void sendFile(const QString&file,const QHostAddress&dest);void sendFile(const QString&file,const QString&dest);void sendMsg(const QString text,const QHostAddress&dest);void sendMsg(const QString text,const QString&dest);void sendEOF();signals:void fileSize(qint64size);void message(const QString&str);void onError(qint32);public slots:void on_connected();void displaySocketError(QAbstractSocket::SocketError e);private:QString filePath;QString msg;bool sendfile;bool sendmsg;};#endif//CLIENT_H//mainwindow.h#ifndef MAINWINDOW_H#define MAINWINDOW_H#include<QMainWindow>#include<QString>namespace Ui{class MainWindow;}class MainWindow:public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget*parent=0);~MainWindow();private:Ui::MainWindow*ui;int sendBytes;qint64blockNumber;qint64maxBytes;bool cleanQuit;bool sendfile;bool sendmsg;private slots:void on_Sendmsg_clicked();void on_Filerev_clicked();void on_Sendfile_clicked();void setProccessBar(qint64r);void updateProccessBar(qint64v);void on_socketDisconnected();void on_socketError(qint32);};#endif//MAINWINDOW_H//Client.cpp#include"Client.h"#include<QByteArray>#include<QDataStream>#include<QFile>#include<QHostAddress>Client::Client(QObject*parent):QTcpSocket(parent){sendfile=false;sendmsg=false;connect(this,SIGNAL(connected()),this,SLOT(on_connected()));connect(this,SIGNAL(error(QAbstractSocket::SocketError)), this,SLOT(displaySocketError(QAbstractSocket::SocketError)));}void Client::sendFile(const QString&file,const QHostAddress&dest) {filePath=file;sendfile=true;connectToHost(dest,5234);qDebug()<<"Send file"<<file;}void Client::sendFile(const QString&file,const QString&dest){filePath=file;sendfile=true;connectToHost(dest,5234);qDebug()<<"Send file"<<file;}void Client::sendMsg(const QString text,const QHostAddress&dest) {sendmsg=true;msg=text;connectToHost(dest,5234);qDebug()<<"Send message"<<text;}void Client::sendMsg(const QString text,const QString&dest){sendmsg=true;msg=text;connectToHost(dest,5234);qDebug()<<"Send message"<<text;}void Client::on_connected(){qDebug()<<"Connected";if(sendfile){QFile file(filePath);if(!file.open(QIODevice::ReadOnly)){emit onError(2);disconnectFromHost();return;}elseemit fileSize(file.size());emit message(tr("Start send!"));QString fileName=file.fileName();fileName=fileName.remove(0,stIndexOf('/')+1);qint64size;QByteArray block;QDataStream out(&block,QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_5_0);out<<qint16(0x0001)<<fileName.toUtf8();size=block.size();write((char*)&size,sizeof(qint64));write(block.data(),size);//flush();if(!waitForBytesWritten(-1)){qDebug()<<"writen Bytes error"<<errorString();throw2;}do{block.clear();out.device()->seek(0);out<<qint16(0x0002)<<file.read(0xFFF0);size=block.size();qDebug()<<"Send Data"<<size<<"byte.";write((char*)&size,sizeof(qint64));write(block.data(),size);if(!waitForBytesWritten(-1)){qDebug()<<"writen Bytes error"<<errorString();throw2;}}while(!file.atEnd());sendEOF();qDebug()<<"FileSend finished.";emit message(tr("Send finished!"));forever/*(int i=0;i<10;i++)*/{if(!waitForDisconnected()){//sendEOF();}else{//qDebug()<<"Number is"<<i<<".";qDebug()<<"GoTo return.";return;}}qDebug()<<"I will disconnected.";sendfile=false;disconnectFromHost();//have Error.}if(sendmsg){qint64size;QByteArray block;QDataStream out(&block,QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_4_0);out<<qint16(0x0004)<<msg.toUtf8();size=block.size();write((char*)&size,sizeof(qint64));write(block.data(),size);sendmsg=false;disconnectFromHost();//have Error.}}void Client::displaySocketError(QAbstractSocket::SocketError e) {qDebug()<<"Error:"<<e<<"\n\t"<<errorString();if(e==QAbstractSocket::HostNotFoundError)emit onError(1);if(e==QAbstractSocket::ConnectionRefusedError)emit onError(3);}void Client::sendEOF(){qint64size;QByteArray block;QDataStream out(&block,QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_4_0);QByteArray data=filePath.toUtf8();data.resize(0x8000);out<<quint16(0x0003)<<data<<filePath.toUtf8();size=block.size();write((char*)&size,sizeof(qint64));write(block.data(),size);if(!waitForBytesWritten(-1))qDebug()<<"Send EOF Error:"<<errorString();elseqDebug()<<"Send EOF";}//main.cpp#include"mainwindow.h"#include<QApplication>int main(int argc,char*argv[]){QApplication a(argc,argv);MainWindow w;w.show();return a.exec();}//mainwindow.cpp#include"mainwindow.h"#include"ui_mainwindow.h"#include"Client.h"#include<QFileDialog>#include<QtNetwork/QtNetwork>#include<QMessageBox>MainWindow::MainWindow(QWidget*parent):QMainWindow(parent),ui(new Ui::MainWindow){ui->setupUi(this);sendBytes=0;blockNumber=0;maxBytes=0;cleanQuit=true;sendfile=false;sendmsg=false;ui->progressBar->setRange(0,1000);ui->progressBar->setValue(0);}MainWindow::~MainWindow()delete ui;}void MainWindow::setProccessBar(qint64r){maxBytes=r;ui->progressBar->setRange(0,r-1);}void MainWindow::updateProccessBar(qint64v){blockNumber++;sendBytes+=v;ui->progressBar->setValue(sendBytes);}void MainWindow::on_Sendmsg_clicked(){cleanQuit=false;sendmsg=true;if(ui->textEdit->toPlainText()==""){QMessageBox::information(this,tr("Error"),tr("Text can not be empty."));return;}ui->Sendmsg->setEnabled(false);Client*client=new Client(this);connect(client,SIGNAL(disconnected()),client,SLOT(deleteLater()));connect(client,SIGNAL(disconnected()),this,SLOT(on_socketDisconnected()));connect(client,SIGNAL(onError(qint32)),this,SLOT(on_socketError(qint32)));client->sendMsg(ui->textEdit->toPlainText(),ui->serveraddr->toPlainText());}void MainWindow::on_Filerev_clicked(){ui->Filepath->setText(QFileDialog::getOpenFileName(this,tr("Open File"),tr("."),tr("All Files(*)")));void MainWindow::on_Sendfile_clicked(){cleanQuit=false;sendfile=true;sendBytes=0;blockNumber=0;maxBytes=0;if(ui->Filepath->toPlainText()==""||ui->serveraddr->toPlainText()==""){QMessageBox::information(this,tr("Error"),tr("Tag and File can not be empty."));return;}ui->Sendfile->setEnabled(false);Client*client=new Client(this);connect(client,SIGNAL(disconnected()),client,SLOT(deleteLater()));connect(client,SIGNAL(disconnected()),this,SLOT(on_socketDisconnected()));connect(client,SIGNAL(fileSize(qint64)),this,SLOT(setProccessBar(qint64)));connect(client,SIGNAL(bytesWritten(qint64)),this,SLOT(updateProccessBar(qint64)));connect(client,SIGNAL(onError(qint32)),this,SLOT(on_socketError(qint32)));client->sendFile(ui->Filepath->toPlainText(),ui->serveraddr->toPlainText());}void MainWindow::on_socketError(qint32e){switch(e){case1:QMessageBox::warning(this,tr("Error"),QString::fromUtf8("目标名错误!\n"),QMessageBox::Close);break;case2:QMessageBox::warning(this,tr("Error"),QString::fromUtf8("文件名错误!\n"),QMessageBox::Close);break;case3:QMessageBox::warning(this,tr("Error"),QString::fromUtf8("连接目标服务器失败!\n"),QMessageBox::Close);}ui->Sendfile->setEnabled(true);}void MainWindow::on_socketDisconnected(){if(sendfile){ui->progressBar->setRange(0,100);ui->progressBar->setValue(100);ui->Sendfile->setEnabled(true);sendfile=false;}if(sendmsg){ui->Sendmsg->setEnabled(true);sendmsg=false;}cleanQuit=true;}服务器端:#Server.proQT+=networkQT+=widgetsQT+=core guigreaterThan(QT_MAJOR_VERSION,4):QT+=widgetsTARGET=ServerTEMPLATE=appSOURCES+=main.cpp\mainwindow.cpp\Thread.cpp\Server.cppHEADERS+=mainwindow.h\Thread.h\Server.hFORMS+=mainwindow.ui//mainwindow.h#ifndef MAINWINDOW_H#define MAINWINDOW_H#include<QMainWindow>#include<QDateTime>#include"Server.h"namespace Ui{class MainWindow;}class MainWindow:public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget*parent=0);Ui::MainWindow*ui;~MainWindow();private:int sendBytes;qint64blockNumber;qint64maxBytes;bool cleanQuit;bool sendfile;bool sendmsg;private slots:void updateEditText(QString text);void updateProccessBar();};#endif//MAINWINDOW_H//Server.h#ifndef SERVER_H#define SERVER_H#include<QTcpServer>class Server:public QTcpServer{Q_OBJECTpublic:explicit Server(QObject*parent=0);void startServer();void stopServer();protected:void incomingConnection(int handle);signals:void rcvmessage(QString);void filerecv();public slots:void rcvmsg(QString text);void file();void displayError(int);void finished();};#endif//SERVER_H//Thread.h#ifndef THREAD_H#define THREAD_H#include"mainwindow.h"#include"ui_mainwindow.h"#include<QThread>#include<QAbstractSocket>#include<QTcpSocket>#include<QByteArray>#include<QDataStream>#include<QDateTime>#include<QFile>#include<QString>class clientThread:public QThread{Q_OBJECTpublic:explicit clientThread(int h,QObject*parent=0);void proccessData(QByteArray&array);protected:void run();signals:void error(int);void message(QString);void filerecv();public slots:void on_socket_readyRead();void on_socket_disconnected();void displaySocketError(QAbstractSocket::SocketError e);private:QFile file;QString fileName;QString text;QTcpSocket s;qint64blockSize;qint64blockNumber;};#endif//THREAD_H//main.cpp#include"mainwindow.h"#include"Server.h"#include<QApplication>int main(int argc,char*argv[]){QApplication a(argc,argv);MainWindow w;w.show();return a.exec();//mainwindow.cpp#include"mainwindow.h"#include"ui_mainwindow.h"MainWindow::MainWindow(QWidget*parent):QMainWindow(parent),ui(new Ui::MainWindow){ui->setupUi(this);ui->progressBar->setRange(0,100);ui->progressBar->setValue(0);Server*ser=new Server(this);connect(ser,SIGNAL(rcvmessage(QString)),this,SLOT(updateEditText(QString)));connect(ser,SIGNAL(filerecv()),this,SLOT(updateProccessBar()));ser->startServer();}MainWindow::~MainWindow(){delete ui;}void MainWindow::updateProccessBar(){ui->progressBar->setValue(100);}void MainWindow::updateEditText(QString text){QDateTime current_date_time=QDateTime::currentDateTime();QString current_time=current_date_time.toString("yyyy-MM-ddhh:mm:ss ddd");ui->msg->append(current_time);ui->msg->append(text);}//Server.cpp#include"Server.h"#include"Thread.h"Server::Server(QObject*parent):QTcpServer(parent){}void Server::startServer(){listen(QHostAddress::Any,5234);qDebug()<<"Server started on port0.0.0.0:5234";}void Server::stopServer(){close();}void Server::incomingConnection(int handle){clientThread*client=new clientThread(handle,this);connect(client,SIGNAL(error(int)),this,SLOT(displayError(int)));connect(client,SIGNAL(finished()),this,SLOT(finished()));connect(client,SIGNAL(finished()),client,SLOT(deleteLater()));connect(client,SIGNAL(message(QString)),this,SLOT(rcvmsg(QString)));connect(client,SIGNAL(filerecv()),this,SLOT(file()));client->start();}void Server::rcvmsg(QString text){emit rcvmessage(text);}void Server::file(){emit filerecv();}void Server::displayError(int e){qDebug()<<"The clientThread have a error."<<e<<".";}void Server::finished()qDebug()<<"a clientThread finished.";}//Thread.cpp#include"Thread.h"#include<QAbstractSocket>#include<QByteArray>#include<QDataStream>#include<QDateTime>#include<QFile>#include<QHostAddress>#include<QString>clientThread::clientThread(int h,QObject*parent):QThread(parent),s(parent)/*s(QAbstractSocket::TcpSocket,parent)*//*,file(parent)*/{blockSize=0;blockNumber=0;s.setSocketDescriptor(h);connect(&s,SIGNAL(disconnected()),this,SLOT(on_socket_disconnected()));connect(&s,SIGNAL(readyRead()),this,SLOT(on_socket_readyRead()));connect(&s,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displaySocketError(QAbstractSocket::SocketError)));}void clientThread::proccessData(QByteArray&array){QDataStream in(&array,QIODevice::ReadOnly);in.setVersion(QDataStream::Qt_4_0);quint16key;QByteArray data;in>>key>>data;blockNumber++;qDebug()<<"BlockNumber"<<blockNumber<<",size:"<<blockSize+sizeof(qint64)<<".";qDebug()<<"\tKey:"<<key<<"\t\tSize:"<<data.size()<<".";switch(key){case0x0001://file namefileName=fileName.fromUtf8(data.data(),data.size());file.setFileName(fileName);if(file.exists(fileName)){qDebug()<<"File was exists.now remove it!";file.remove(fileName);}if(!file.open(QIODevice::WriteOnly)){qDebug()<<"Can not open file"<<file.fileName()<<".";throw2;}break;case0x0002://file datafile.write(data.data(),data.size());file.flush();break;case0x0003://file EOFqDebug()<<"File transt finished.";file.close();emit filerecv();s.disconnectFromHost();break;//emit finished();case0x0004:qDebug()<<"Receive message";text=text.fromUtf8(data.data());emit message(text);qDebug()<<text;break;default:;}}void clientThread::run(){qDebug()<<"New connect from"<<s.peerAddress().toString()<<":" <<s.peerPort()<<".";exec();}void clientThread::on_socket_disconnected(){qDebug()<<"socket disconnected.";exit();//emit finished();}void clientThread::on_socket_readyRead(){while(s.bytesAvailable()>=sizeof(quint64)){if(blockSize==0){if(s.bytesAvailable()<sizeof(qint64))return;s.read((char*)&blockSize,sizeof(qint64));//read blockSize }if(s.bytesAvailable()<blockSize)//have no enugh datareturn;QByteArray data=s.read(blockSize);proccessData(data);blockSize=0;}}void clientThread::displaySocketError(QAbstractSocket::SocketError e) {qDebug()<<"Error:socket have error"<<e<<"\n\t"<<s.errorString() <<".";qDebug()<<"Removed"<<file.fileName()<<".";if(file.isOpen())file.close();elsereturn;if(!file.fileName().isEmpty())file.remove(fileName);elsereturn;emit error(2);//exit();}。