日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Qt?TCP實現簡單通信功能_C 語言

作者:xundao_803817 ? 更新時間: 2022-10-18 編程語言

本文實例為大家分享了Qt TCP實現簡單通信的具體代碼,供大家參考,具體內容如下

在.pro文件中添加網絡模塊 Qt += network

服務端:

1. 創建QTcpServer 對象,用于監聽,創建套接字等;

QTcpServer * serverSocket = new QTcpServer(this);

2.進行監聽,通過QTcpServer對象 QTcpServer::listen();

bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);

例子:

// 獲取單行輸入框輸入的數為端口號
short port = ui->lineEdit->text().toInt();
tcpServer->listen(QHostAddress::Any, port); // QHostAddress::Any表示自動綁定

3.使用信號槽,connect(), 判斷是否有客戶端來連接,QTcpServer::newConnection();

[signal] void QTcpServer::newConnection()

例子:

// 3.基于 QTcpServer::newConnection() 信號檢測是否有新客戶端連接
connect(tcpServer, &QTcpServer::newConnection, this, [=]()
? ? {
? ? ? ? // 創建用于通信的套接字
? ? ? ? // 4.如果有新的客戶端連接調用 QTcpSocket* QTcpServer::nextPendingConnection()
? ? ? ? // 在通信編輯框中顯示成功與客戶端取得連接
? ? ? ? // 5.準備與客戶端通信
? ? ? ? // 6.判斷客戶端是否斷開連接 ? ?
? ? });

4.在步驟3的基礎上,創建套接字,QTcpSocket socketServer = QTcpServer::nextPendingConnection();

5.在步驟3的基礎上,使用信號槽connect(),判斷是否接收客戶端發了 的信息QTcpSocket::readyRead();

6. 在步驟5的基礎上,通過套接字調用readAll() ,讀取客戶端發來的信息;

7.在步驟3的基礎上,通過套接字判斷客戶端是否下線,關閉套接字;

客戶端:

1. 創建套接字對象,用于通信 QTcpSocket *clientSocket = new QTcpSocket(this);

2. 調用信號槽,connect() ,判斷是否成功連接服務端connected;

3. 調用信號槽,connect() , 判斷是否接受來著服務端發來的信息 readyRead();

4. 在步驟3的基礎上,利用套接字對象調用readAll() 方法,讀取服務端發來的消息;

5. 利用套接字調用write() 方法,將消息發送給服務端;

6. 調用信號槽,connect() , 判斷是否斷開連接,釋放套接字;

服務端代碼:

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
?
#include "QDebug"
#include <QMessageBox>
?
MainWindow::MainWindow(QWidget *parent) :
? ? QMainWindow(parent),
? ? ui(new Ui::MainWindow)
{
? ? ui->setupUi(this);
?
? ? // 設置窗口名稱
? ? setWindowTitle(QString("Server-TCP"));
? ? setWindowIcon(QIcon(QPixmap("D:\\BaiduNetdiskDownload\\Res WWW\\picture\\ico\\01_副本.png")));
?
? ? // 剛進來是將連接狀態圖片置成灰色的
? ? m_pixmap.load(QString("D:\\BaiduNetdiskDownload\\Res WWW\\picture\\ico\\01_副本_副本.png"));
?
? ? // 2.socket 通信
? ? //tcpSocket = new QTcpSocket();
? ? // 獲取套接字
? ? // 服務端通信流程
? ? // 1.創建套接字服務器 QTcpServer對象
? ? tcpServer = new QTcpServer(this);
? ? // 2.通過QTcpServer對象設置監聽,即QTcpServer::listen()
? ? // 3.基于 QTcpServer::newConnection() 信號檢測是否有新客戶端連接
? ? connect(tcpServer, &QTcpServer::newConnection, this, [=]()
? ? {
? ? ? ? // 成功連接則切換圖片顏色
? ? ? ? m_pixmap.load(QString("D:\\BaiduNetdiskDownload\\Res WWW\\picture\\ico\\01_副本.png"));
?
? ? ? ? // 創建用于通信的套接字
? ? ? ? // 4.如果有新的客戶端連接調用 QTcpSocket* QTcpServer::nextPendingConnection()
? ? ? ? tcpSocket = tcpServer->nextPendingConnection();
? ? ? ? // 在通信編輯框中顯示成功與客戶端取得連接
? ? ? ? ui->textEdit->append("成功與客戶端取得連接!!!");
? ? ? ? // 5.準備與客戶端通信
? ? ? ? connect(tcpSocket, &QTcpSocket::readyRead, this, [=]()
? ? ? ? {
? ? ? ? ? ? // 調用套接字讀取客戶端發的數據
? ? ? ? ? ? QString acceptText = tcpSocket->readAll(); // QByteArray 可以強制轉成 QString
? ? ? ? ? ? // 將讀取到的數據寫到通信編輯框中
? ? ? ? ? ? ui->textEdit->append("客戶端say:" + acceptText);
? ? ? ? });
?
? ? ? ? // 6.判斷客戶端是否斷開連接
? ? ? ? connect(tcpSocket, &QTcpSocket::disconnected, this, [=]()
? ? ? ? {
? ? ? ? ? ? //QMessageBox(, QMessageBox::Warning, );
? ? ? ? ? ? QMessageBox::warning(this, "連接狀態", "客戶端已斷開連接");
? ? ? ? ? ? tcpSocket->deleteLater();
? ? ? ? ? ? // 將連接狀態圖片置成灰色的
? ? ? ? ? ? m_pixmap.load(QString("D:\\BaiduNetdiskDownload\\Res WWW\\picture\\ico\\01_副本_副本.png"));
?
? ? ? ? ? ? //tcpServer->deleteLater();
? ? ? ? });
?
? ? });
?
? ? // 1.狀態欄顯示信息
? ? showMessageStatusBar();
}
?
MainWindow::~MainWindow()
{
? ? delete ui;
}
?
// 狀態欄添加提示信息
void MainWindow::showMessageStatusBar()
{
? ? // 設置窗口名稱
? ? //QWidget::windowTitleChanged("Server-TCP");
? ? //ui->statusBar->setWindowTitle();
?
? ? // 通過加載QLable給狀態欄顯示文本
? ? QLabel *pLable = new QLabel();
? ? QLabel *lableText = new QLabel(QString::fromUtf8("連接狀態:"));
?
? ? //lableText->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
? ? //pLable->setMinimumWidth(this->width()/2);
?
? ? //= new QLabel(QString::fromUtf8("連接狀態:"));
? ? // 設置lable標簽的大小
? ? //pLable->setMinimumSize(pLable->sizeHint());
? ? pLable->setFixedSize(30, 30);
?
? ? m_pixmap.scaled(pLable->width(), pLable->height());
? ? // 顯示圖片
? ? pLable->setPixmap(m_pixmap);
? ? // 按比例縮小圖片
?
? ? //pLable->setFixedSize(QSize(50,50));
? ? // 設置狀態欄樣式
? ? //ui->statusBar->setStyleSheet(QString("QString::item{border:0px")); ?// 不顯示邊框
? ? // 將標簽加入到狀態欄中
? ? ui->statusBar->addWidget(lableText);
? ? ui->statusBar->addPermanentWidget(pLable);//
}
?
// 處理點擊啟動服務器,進行監聽
void MainWindow::on_pushButton_clicked()
{
? ? //qDebug() << "點擊了 啟動服務器按鈕\n";
? ? // 獲取輸入框輸入的數為端口號
? ? short port = ui->lineEdit->text().toInt();
? ? tcpServer->listen(QHostAddress::Any, port);
}
?
// 將數據發生給客戶端
void MainWindow::on_pushButton_2_clicked()
{
? ? // 將發送數據編輯欄的文本通過套接字發生給客戶端
? ? tcpSocket->write(ui->textEdit_2->toPlainText().toUtf8());
? ? // 需要將要發生的數據寫到通信編輯欄中
? ? ui->textEdit->append("服務端say:" + ui->textEdit_2->toPlainText().toUtf8());
? ? // 清空發送消息編輯框
? ? ui->textEdit_2->clear();
}

mainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
?
#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>
?
?
namespace Ui {
class MainWindow;
}
?
class MainWindow : public QMainWindow
{
? ? Q_OBJECT
?
public:
? ? explicit MainWindow(QWidget *parent = nullptr);
? ? ~MainWindow();
?
? ? // 在狀態欄中設置文本+圖標
? ? void showMessageStatusBar();
?
? ? QTcpServer* tcpServer;
? ? QTcpSocket* tcpSocket;
?
private slots:
? ? void on_pushButton_clicked();
?
? ? void on_pushButton_2_clicked();
?
private:
? ? Ui::MainWindow *ui;
? ? // 用于加載圖片路徑
? ? QPixmap m_pixmap;
};
?
#endif // MAINWINDOW_H

程序UI

客戶端:

client.cpp

#include "client.h"
#include "ui_client.h"
?
Client::Client(QWidget *parent) :
? ? QMainWindow(parent),
? ? ui(new Ui::Client)
{
? ? ui->setupUi(this);
?
? ? // 通信流程
? ? //1、創建套接字對象
? ? clientSocket = new QTcpSocket(this);
? ? //2、調用QTcpSocket::connectToHost() 綁定服務端IP和端口
?
? ? //3、通過套接字與服務端進行通信 收發
? ? // 判斷是否成功連接服務端 開始讀取服務端發來的信息
? ? connect(clientSocket, &QTcpSocket::readyRead, this, [=]()
? ? {
? ? ? ? // 通過套接字讀取發來的信息
? ? ? ? QByteArray receiveAll = clientSocket->readAll();
? ? ? ? // 將獲取到的信息顯示到通信編輯欄中
? ? ? ? ui->textEdit_Record->append("服務端say:" + receiveAll);
? ? });
?
? ? // 開始的時候斷開連接按鈕置成不可用狀態
? ? ui->disConBtn->setEnabled(false);
?
? ? // 判斷是否連接成功
? ? connect(clientSocket, &QTcpSocket::connected, this, [=]()
? ? {
? ? ? ? // 將成功連接顯示到通信記錄編輯欄中
? ? ? ? ui->textEdit_Record->append("成功與服務端取得連接!!!");
? ? ? ? // 將斷開連接置成可用狀態
? ? ? ? ui->disConBtn->setEnabled(true);
? ? });
?
? ? // 判斷是否斷開連接
? ? connect(clientSocket, &QTcpSocket::disconnected, this, [=]()
? ? {
? ? ? ? // 將服務端斷開連接顯示到通信編輯框中
? ? ? ? ui->textEdit_Record->append("注意服務端已斷開連接!!!");
? ? ? ? // 將連接服務端按鈕置成不可用狀態
? ? ? ? ui->conBtn->setEnabled(false);
? ? });
?
}
?
Client::~Client()
{
? ? delete ui;
}
?
// 點擊按鈕連接服務器,綁定地址與端口
void Client::on_conBtn_clicked()
{
? ? // 獲取編輯框中的ip和端口
? ? unsigned short port = ui->lineEdit_port->text().toUShort();
? ? QString addr = ui->lineEdit_add->text();
? ? clientSocket->connectToHost(addr, port);
? ? // 需要將按鈕置成不可用狀態
? ? ui->conBtn->setEnabled(false);
}
?
// 斷開連接
void Client::on_disConBtn_clicked()
{
? ? //clientSocket->disconnected();
? ? // 關閉套接字
? ? clientSocket->close();
? ? // 將客戶端斷開連接提示顯示到通信編輯框中
? ? ui->textEdit_Record->append("注意客戶端已斷開連接!!!");
? ? // 將連接服務端按鈕置成可用狀態
? ? ui->conBtn->setEnabled(true);
}
?
// 點擊按鈕發送數據
void Client::on_sendBtn_clicked()
{
? ? // 獲取發送信息編輯框的文本
? ? //ui->textEdit_Send->toPlainText().toUtf8();
?
? ? // 將獲取到的信息發送給服務端
? ? clientSocket->write(ui->textEdit_Send->toPlainText().toUtf8());
? ? // 將發送的信息顯示到通信記錄編輯框中
? ? ui->textEdit_Record->append(ui->textEdit_Send->toPlainText().toUtf8());
? ? // 需要將發送編輯框清空緩存
? ? ui->textEdit_Send->clear();
}

client.h

#ifndef CLIENT_H
#define CLIENT_H
?
#include <QMainWindow>
#include <QTcpSocket>
?
namespace Ui {
class Client;
}
?
class Client : public QMainWindow
{
? ? Q_OBJECT
?
public:
? ? explicit Client(QWidget *parent = nullptr);
? ? ~Client();
?
private slots:
? ? void on_conBtn_clicked();
?
? ? void on_disConBtn_clicked();
?
? ? void on_sendBtn_clicked();
?
private:
? ? Ui::Client *ui;
?
? ? // 創建套接字
? ? QTcpSocket * clientSocket;
};
?
#endif // CLIENT_H

程序UI

原文鏈接:https://blog.csdn.net/m0_60178310/article/details/124989566

欄目分類
最近更新