QT示例:基于TCP点对点Socket通讯
生活随笔
收集整理的這篇文章主要介紹了
QT示例:基于TCP点对点Socket通讯
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
QT示例:基于TCP點對點通訊
- 一、 概述
- 二、TCP 協議工作原理
- 三、TCP 編程模型
- 四、基于TCP點對點通訊示例
- 1、客戶端
- 2、客戶端Client示例
- 3、服務器
- 4、服務器server示例
下載:基于TCP點對點通訊
一、 概述
二、TCP 協議工作原理
三、TCP 編程模型
四、基于TCP點對點通訊示例
1、客戶端
客戶端的代碼比服務器稍簡單,總的來說,使用QT中的QTcpSocket類與服務器進行通信只需要以下5步:
1)創建QTcpSocket套接字對象
2)使用這個對象連接服務器
socket->connectToHost(IP, port);3)使用write函數向服務器發送數據
socket->write(data);4)當socket接收緩沖區有新數據到來時,會發出readRead()信號,因此為該信號添加槽函數以讀取數據
QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);void myWidget::socket_Read_Data() {QByteArray buffer;//讀取緩沖區數據buffer = socket->readAll(); }5)斷開與服務器的連接(關于close()和disconnectFromHost()的區別,可以按F1看幫助)
socket->disconnectFromHost(); socket->close();2、客戶端Client示例
.pro文件添加:
QT +=networkmyWidget.h 添加:
//#include <QtNetwork> #include <QTcpSocket> #include <QMessageBox>namespace Ui { class myWidget; }class myWidget : public QWidget {Q_OBJECTpublic:explicit myWidget(QWidget *parent = 0);~myWidget();private slots:void on_pushButton_connect_clicked(); // 連接按鈕void socket_Read_Data(); // 數據流讀取void on_pushButton_send_clicked(); // 發送數據void socket_Disconnected(); // 連接中斷 private:Ui::myWidget *ui;QTcpSocket *socket;QPalette Pal0,Pal1; // 調色板 };myWidget.cpp 添加:
#include "mywidget.h" #include "ui_mywidget.h"myWidget::myWidget(QWidget *parent):QWidget(parent),ui(new Ui::myWidget) {ui->setupUi(this);// 一、創建QTcpSocket套接字對象socket = new QTcpSocket;ui->pushButton_send->setEnabled(false);ui->lineEdit_IP->setText("192.168.1.100");ui->lineEdit_port->setText("8010");Pal0 =ui->pushButton_connect->palette();Pal1.setColor(QPalette::ButtonText,Qt::red); // 只能對按鈕文本、窗口文本的動態顏色設置//連接信號槽QObject::connect(socket, &QTcpSocket::readyRead, this, &myWidget::socket_Read_Data);QObject::connect(socket, &QTcpSocket::disconnected, this, &myWidget::socket_Disconnected); }myWidget::~myWidget() {delete this->socket;delete ui; }// 二、連接服務器 void myWidget::on_pushButton_connect_clicked() {if(ui->pushButton_connect->text() == tr("連接")){//獲取IP地址QString IP = ui->lineEdit_IP->text();//獲取端口號int port = ui->lineEdit_port->text().toInt();//取消已有的連接socket->abort();//連接服務器(使用socket對象連接服務器)socket->connectToHost(IP, port);//等待連接成功if(!socket->waitForConnected(30000)){QMessageBox::information(this,tr("提示"),tr("Connection failed!"),QMessageBox::Ok);return;}QMessageBox::information(this,tr("提示"),tr("Connect successfully!"),QMessageBox::Ok);// 更新界面ui->pushButton_send->setEnabled(true);ui->pushButton_connect->setText("斷開連接");ui->pushButton_connect->setPalette(Pal1);}else{//斷開連接socket->disconnectFromHost();socket->close();// 更新界面ui->pushButton_send->setEnabled(false);ui->pushButton_connect->setText("連接");ui->pushButton_connect->setPalette(Pal0);} }// 三、接受/讀取數據:使用socket的write函數向客戶端發送數據 void myWidget::socket_Read_Data() {// 讀取緩沖區數據QByteArray buffer= socket->readAll();if(!buffer.isEmpty()){QString str =ui->textEdit_receive->toPlainText();str += buffer+"\n";// 刷新顯示接受到的數據ui->textEdit_receive->setText(str);} }// 四、發送按鈕:使用socket的write函數向客戶端發送數據 void myWidget::on_pushButton_send_clicked() {//獲取文本框內容并以ASCII碼形式發送socket->write(ui->textEdit_send->toPlainText().toLatin1());socket->flush(); // 沖掉 緩存 }// 五、斷開連接 void myWidget::socket_Disconnected() {ui->pushButton_send->setEnabled(false);QMessageBox::information(this, tr("提示"),tr("Disconnected!"), QMessageBox::Ok); }界面:
3、服務器
二、服務器
服務器使用到了QTcpSocket類和QTcpSever類。用到了6個步驟:
1)創建QTcpSever對象
2)偵聽一個端口,使得客戶端可以使用這個端口訪問服務器
server->listen(QHostAddress::Any, port)3)當服務器被客戶端訪問時,會發出newConnection()信號,因此為該信號添加槽函數,并用一個QTcpSocket對象接受客戶端訪問
connect(server,&QTcpServer::newConnection,this,&mywidget::server_New_Connect);void MainWindow::server_New_Connect() {//獲取客戶端連接(獲得連接過來的客戶端信息)socket = server->nextPendingConnection(); }4)使用socket的write函數向客戶端發送數據
socket->write(data);5)當socket接收緩沖區有新數據到來時,會發出readRead()信號,因此為該信號添加槽函數以讀取數據
QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);void MainWindow::socket_Read_Data() {QByteArray buffer;//讀取緩沖區數據buffer = socket->readAll(); }6)取消偵聽
server->close();4、服務器server示例
.pro文件添加:
QT +=networkmyWidget.h 添加:
//#include <QtNetwork> #include <QTcpServer> #include <QTcpSocket> #include <QMessageBox>namespace Ui { class myWidget; }class myWidget : public QWidget {Q_OBJECTpublic:explicit myWidget(QWidget *parent = 0);~myWidget();private slots:void server_New_Connect();void socket_Read_Data();void socket_Disconnected();void on_pushButton_listen_clicked();void on_pushButton_send_clicked();private:Ui::myWidget *ui; private:QTcpServer *server;QTcpSocket *socket;QPalette Pal0,Pal1; // 調色板bool socket_IsConnected =false ;};myWidget.cpp 添加:
#include "mywidget.h" #include "ui_mywidget.h"myWidget::myWidget(QWidget *parent):QWidget(parent),ui(new Ui::myWidget) {ui->setupUi(this);ui->lineEdit_port->setText("8010");ui->lineEdit_ip->setText(QNetworkInterface().allAddresses().at(1).toString()); //獲取本地IPui->lineEdit_ip->setEnabled(false); // 只能用主機IP 作為服務端ui->pushButton_send->setEnabled(false);Pal0=ui->pushButton_listen->palette();Pal1.setColor(QPalette::ButtonText,Qt::red); // 此方式 只能對按鈕文本、窗口文本的動態顏色設置// 一 、創建QTcpSever對象;server = new QTcpServer();//連接信號槽(服務端被訪問時,自動觸發newconnection 信號,綁定槽函數 server new connect)connect(server,&QTcpServer::newConnection,this,&myWidget::server_New_Connect);}myWidget::~myWidget() {server->close();server->deleteLater();delete ui; }// 二、監聽按鈕:監聽端口 void myWidget::on_pushButton_listen_clicked() {if(ui->pushButton_listen->text()==tr("開始監聽")){// 1.獲取端口號QHostAddress IP(ui->lineEdit_ip->text()); // 服務器IPint port = ui->lineEdit_port->text().toInt();// 2.監聽指定的端口(主機地址)if(!server->listen(IP,port)){// 若出錯,則輸出錯誤信息QMessageBox::warning(this, tr("錯誤"),tr("監聽失敗!"), QMessageBox::Ok);return;}ui->pushButton_listen->setText("取消監聽"); // 修改鍵文字ui->pushButton_listen->setPalette(Pal1);// ui->pushButton_listen->setStyleSheet("background-color:rgb(255,255,0)"); // 改變按鈕背景顏色}else{//if(socket->state() == QAbstractSocket::ConnectedState) // 若socket沒有指定對象會有異常if(socket_IsConnected){//關閉連接socket->disconnectFromHost();socket_IsConnected =false;}// 4.關閉服務端server->close();QMessageBox::information(this, tr("提示"),tr("已取消監聽"), QMessageBox::Ok);// 更新界面ui->pushButton_listen->setText("開始監聽");ui->pushButton_listen->setPalette(Pal0);ui->pushButton_send->setEnabled(false);} }// 三、建立新連接(當服務器接收到客戶端信號時) void myWidget::server_New_Connect() {//獲取客戶端連接(獲得連接過來的客戶端信息)socket = server->nextPendingConnection();//連接QTcpSocket的信號槽,以讀取新數據(服務器接收到客戶端數據后,自動觸發 readyRead 信號)QObject::connect(socket, &QTcpSocket::readyRead, this, &myWidget::socket_Read_Data);// 關閉連接(客戶端斷開連接后,自動觸發 disconnect 信號)QObject::connect(socket, &QTcpSocket::disconnected, this, &myWidget::socket_Disconnected);ui->pushButton_send->setEnabled(true);QMessageBox::information(this,tr("提示"),tr("A Client connect!"),QMessageBox::Ok);socket_IsConnected= true; } // 四、接受/讀取數據:使用socket的write函數向客戶端發送數據 void myWidget::socket_Read_Data() {// 讀取緩沖區數據QByteArray buffer= socket->readAll();if(!buffer.isEmpty()){QString str =ui->textEdit_receive->toPlainText();str +=buffer+"\n";// 刷新顯示接受到的數據ui->textEdit_receive->setText(str);} }// 五、發送按鈕:使用socket的write函數向客戶端發送數據 void myWidget::on_pushButton_send_clicked() {//獲取文本框內容并以ASCII碼形式發送(Latin1 編碼規范)socket->write(ui->textEdit_send->toPlainText().toLatin1());socket->flush(); }// 六、斷開連接 void myWidget::socket_Disconnected() {ui->pushButton_send->setEnabled(false);QMessageBox::information(this, tr("提示"),tr("Disconnected!"), QMessageBox::Ok); }界面:
總結
以上是生活随笔為你收集整理的QT示例:基于TCP点对点Socket通讯的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MATLAB判断数据是否为NaN
- 下一篇: s3c2440移植MQTT