世界看點:Qt 實現(xiàn)簡單的TCP通信

這段時間用到了QT的TCP通信,做了初步的學(xué)習(xí)與嘗試,編寫了一個客戶端和服務(wù)器基于窗口通信的小例程。

使用QT的網(wǎng)絡(luò)套接字需要.pro文件中加入一句:

QT += network

一、客戶端


(相關(guān)資料圖)

1、客戶端的代碼比服務(wù)器稍簡單,總的來說,使用QT中的QTcpSocket類與服務(wù)器進行通信只需要以下5步:

(1)創(chuàng)建QTcpSocket套接字對象

socket = new QTcpSocket();

(2)使用這個對象連接服務(wù)器

socket->connectToHost(IP, port);

(3)使用write函數(shù)向服務(wù)器發(fā)送數(shù)據(jù)

socket->write(data)

(4)當socket接收緩沖區(qū)有新數(shù)據(jù)到來時,會發(fā)出readRead()信號,因此為該信號添加槽函數(shù)以讀取數(shù)據(jù)

QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);void MainWindow::socket_Read_Data(){QByteArray buffer;//讀取緩沖區(qū)數(shù)據(jù)buffer = socket->readAll();}

(5)斷開與服務(wù)器的連接(關(guān)于close()和disconnectFromHost()的區(qū)別,可以按F1看幫助)

socket->disconnectFromHost();

2、以下是客戶端的例程

首先是mainwindow.h文件:

//mainwindow.h#ifndef MAINWINDOW_H#define MAINWINDOW_H#include #include namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();private slots:void on_pushButton_Connect_clicked();void on_pushButton_Send_clicked();void socket_Read_Data();void socket_Disconnected();private:Ui::MainWindow *ui;QTcpSocket *socket;};#endif // MAINWINDOW_H

然后是mainwindow.cpp文件:

//mainwindow.cpp#include \"mainwindow.h\"#include \"ui_mainwindow.h\"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow){ui->setupUi(this);socket = new QTcpSocket();//連接信號槽QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);QObject::connect(socket, &QTcpSocket::disconnected, this, &MainWindow::socket_Disconnected);ui->pushButton_Send->setEnabled(false);ui->lineEdit_IP->setText(\"127.0.0.1\");ui->lineEdit_Port->setText(\"8765\");}MainWindow::~MainWindow(){delete this->socket;delete ui;}void MainWindow::on_pushButton_Connect_clicked(){if(ui->pushButton_Connect->text() == tr(\"連接\")){QString IP;int port;//獲取IP地址IP = ui->lineEdit_IP->text();//獲取端口號port = ui->lineEdit_Port->text().toInt();//取消已有的連接socket->abort();//連接服務(wù)器socket->connectToHost(IP, port);//等待連接成功if(!socket->waitForConnected(30000)){qDebug() << \"Connection failed!\";return;}qDebug() << \"Connect successfully!\";//發(fā)送按鍵使能ui->pushButton_Send->setEnabled(true);//修改按鍵文字ui->pushButton_Connect->setText(\"斷開連接\");}else{//斷開連接socket->disconnectFromHost();//修改按鍵文字ui->pushButton_Connect->setText(\"連接\");ui->pushButton_Send->setEnabled(false);}}void MainWindow::on_pushButton_Send_clicked(){qDebug() << \"Send: \" << ui->textEdit_Send->toPlainText();//獲取文本框內(nèi)容并以ASCII碼形式發(fā)送socket->write(ui->textEdit_Send->toPlainText().toLatin1());socket->flush();}void MainWindow::socket_Read_Data(){QByteArray buffer;//讀取緩沖區(qū)數(shù)據(jù)buffer = socket->readAll();if(!buffer.isEmpty()){QString str = ui->textEdit_Recv->toPlainText();str+=tr(buffer);//刷新顯示ui->textEdit_Recv->setText(str);}}void MainWindow::socket_Disconnected(){//發(fā)送按鍵失能ui->pushButton_Send->setEnabled(false);//修改按鍵文字ui->pushButton_Connect->setText(\"連接\");qDebug() << \"Disconnected!\";}

最后是ui的設(shè)計:

二、服務(wù)器

1、服務(wù)器除了使用到了QTcpSocket類,還需要用到QTcpSever類。即便如此,也只是比客戶端復(fù)雜一點點,用到了6個步驟:

(1)創(chuàng)建QTcpSever對象

server = new QTcpServer();

(2)偵聽一個端口,使得客戶端可以使用這個端口訪問服務(wù)器

server->listen(QHostAddress::Any, port);

(3)當服務(wù)器被客戶端訪問時,會發(fā)出newConnection()信號,因此為該信號添加槽函數(shù),并用一個QTcpSocket對象接受客戶端訪問

connect(server,&QTcpServer::newConnection,this,&MainWindow::server_New_Connect);void MainWindow::server_New_Connect(){//獲取客戶端連接socket = server->nextPendingConnection();}

(4)使用socket的write函數(shù)向客戶端發(fā)送數(shù)據(jù)

socket->write(data)

(5)當socket接收緩沖區(qū)有新數(shù)據(jù)到來時,會發(fā)出readRead()信號,因此為該信號添加槽函數(shù)以讀取數(shù)據(jù)

QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);void MainWindow::socket_Read_Data(){QByteArray buffer;//讀取緩沖區(qū)數(shù)據(jù)buffer = socket->readAll();}

(6)取消偵聽

server->close();

2、以下是服務(wù)器的例程

首先是mainwindow.h文件:

//mainwindow.h#ifndef MAINWINDOW_H#define MAINWINDOW_H#include #include #include namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();private slots:void on_pushButton_Listen_clicked();void on_pushButton_Send_clicked();void server_New_Connect();void socket_Read_Data();void socket_Disconnected();private:Ui::MainWindow *ui;QTcpServer* server;QTcpSocket* socket;};#endif // MAINWINDOW_H

然后是mainwindow.cpp文件:

#include \"mainwindow.h\"#include \"ui_mainwindow.h\"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow){ui->setupUi(this);ui->lineEdit_Port->setText(\"8765\");ui->pushButton_Send->setEnabled(false);server = new QTcpServer();//連接信號槽connect(server,&QTcpServer::newConnection,this,&MainWindow::server_New_Connect);}MainWindow::~MainWindow(){server->close();server->deleteLater();delete ui;}void MainWindow::on_pushButton_Listen_clicked(){if(ui->pushButton_Listen->text() == tr(\"偵聽\")){//從輸入框獲取端口號int port = ui->lineEdit_Port->text().toInt();//監(jiān)聽指定的端口if(!server->listen(QHostAddress::Any, port)){//若出錯,則輸出錯誤信息qDebug()<errorString();return;}//修改按鍵文字ui->pushButton_Listen->setText(\"取消偵聽\");qDebug()<< \"Listen succeessfully!\";}else{/*//如果正在連接(點擊偵聽后立即取消偵聽,若socket沒有指定對象會有異常,應(yīng)修正——2017.9.30)if(socket->state() == QAbstractSocket::ConnectedState){//關(guān)閉連接socket->disconnectFromHost();}*/socket->abort();//取消偵聽server->close();//修改按鍵文字ui->pushButton_Listen->setText(\"偵聽\");//發(fā)送按鍵失能ui->pushButton_Send->setEnabled(false);}}void MainWindow::on_pushButton_Send_clicked(){qDebug() << \"Send: \" << ui->textEdit_Send->toPlainText();//獲取文本框內(nèi)容并以ASCII碼形式發(fā)送socket->write(ui->textEdit_Send->toPlainText().toLatin1());socket->flush();}void MainWindow::server_New_Connect(){//獲取客戶端連接socket = server->nextPendingConnection();//連接QTcpSocket的信號槽,以讀取新數(shù)據(jù)QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);QObject::connect(socket, &QTcpSocket::disconnected, this, &MainWindow::socket_Disconnected);//發(fā)送按鍵使能ui->pushButton_Send->setEnabled(true);qDebug() << \"A Client connect!\";}void MainWindow::socket_Read_Data(){QByteArray buffer;//讀取緩沖區(qū)數(shù)據(jù)buffer = socket->readAll();if(!buffer.isEmpty()){QString str = ui->textEdit_Recv->toPlainText();str+=tr(buffer);//刷新顯示ui->textEdit_Recv->setText(str);}}void MainWindow::socket_Disconnected(){//發(fā)送按鍵失能ui->pushButton_Send->setEnabled(false);qDebug() << \"Disconnected!\";}

最后是ui的設(shè)計:

三、運行結(jié)果

【領(lǐng) QT開發(fā)教程 學(xué)習(xí)資料, 點擊下方鏈接莬費領(lǐng)取↓↓ ,先碼住不迷路~】

點擊這里:

關(guān)鍵詞:
圖片版權(quán)歸原作者所有,如有侵權(quán)請聯(lián)系我們,我們立刻刪除。
新化月報網(wǎng)報料熱線:886 2395@qq.com

相關(guān)文章

你可能會喜歡

最近更新

推薦閱讀