文章目錄
- 一、TCP 客戶端
- 二、TCP 服務器
原始碼: NetToolsTest
QT Widge 其它文章請點擊這里: QT Widget 學習筆記
姊妹篇:
Qt TCP/UDP 網路協議入門實操(一)TCP通訊
Qt TCP/UDP 網路協議入門實操(二)UDP通訊
Qt TCP/UDP 網路協議入門實操(補充)
此文只是最簡單的入門學習,需進一步可以看 飛揚青云 大佬的原始碼 QWidgetDemo, 選擇 nettool ,已經是非常完善的網路除錯助手了
關于TCP/IP協議可詳看:TCP/IP協議詳解 - 知乎 具體就不介紹
總的來說,TCP/IP 通訊分為客戶端和服務器通訊,而底層 Qt 都已經都封裝好了,如果僅僅只是簡單使用,還是相當簡單的
在此只需弄懂 QTcpServer(監聽套接字)和QTcpSocket(通訊套接字)
監聽套接字,顧名思義,監聽關于各種通訊的狀態,一旦進行通訊,監聽套接字會啟動通訊套接字,進行通訊
一、TCP 客戶端
● Qt 中使用 TCP 客戶端通訊演示

左側為成熟的網路除錯助手
● 實操流程圖

客戶端使用 connectToHost 函式主動連接服務器后,服務器會觸發 newConnectio 這個槽函式,并進行取出 QTcpServer(監聽套接字),將相關內容取出并賦給QTcpSocket(通訊套接字),
客戶端向服務器發送資料,觸發readyRead(),進行處理,彼此傳遞時,原理都是這樣的,
● 代碼
tcpclient.cpp
#include "tcpclient.h"
#include "ui_tcpclient.h"
TcpClient::TcpClient(QWidget *parent) :
QWidget(parent),
ui(new Ui::TcpClient)
{
ui->setupUi(this);
initForm();
}
TcpClient::~TcpClient()
{
delete ui;
}
//1 ui
//2. 初始化
//① 創建 QTcpSocket 套接字物件
//② 建立socket 接識訓沖資料的信號槽(readyRead)
void TcpClient::initForm()
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
}
//3. 連接服務器 (socket->connectToHost)
// 在連接按鍵中,獲取手動輸入的服務器IP地址和埠號
void TcpClient::on_btnConnect_clicked()
{
TcpServerIP = ui->txtServerIP->text().trimmed();
TcpServerPort = ui->txtServerPort->text().trimmed().toInt();
if (ui->btnConnect->text() == "連接") {
socket->abort();
socket->connectToHost(TcpServerIP, static_cast<quint16>(TcpServerPort));
ui->btnConnect->setText("斷開");
} else {
socket->abort();
ui->btnConnect->setText("連接");
}
}
//4.1 接收服務器資料 (socket->readAll())
void TcpClient::readData() {
QByteArray data = socket->readAll();
if (data.length() <= 0) return;
QString strData = "[接收] " + TcpServerIP + " " + QString::number(TcpServerPort) + " " + data + "";
ui->txtMain->setTextColor(QColor("red"));
ui->txtMain->append(strData);
}
// 4.2發送資料到服務器
void TcpClient::on_btnSend_clicked()
{
QString data = ui->cboxData->currentText();
if (data.length() <= 0) return;
QByteArray buffer = data.toUtf8();
socket->write(buffer);
QString strData = "[發送] " + TcpServerIP + " " + QString::number(TcpServerPort) + " " + buffer + "";
ui->txtMain->setTextColor(QColor("darkgreen"));
ui->txtMain->append(strData);
}
tcpclient.h
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QWidget>
#include <QtNetwork>
namespace Ui {
class TcpClient;
}
class TcpClient : public QWidget
{
Q_OBJECT
public:
TcpClient(QWidget *parent = nullptr);
~TcpClient();
void initForm();
private slots:
void readData();
private slots:
void on_btnConnect_clicked();
void on_btnSend_clicked();
private:
Ui::TcpClient *ui;
QTcpSocket *socket;
QString TcpServerIP; //服務器IP
int TcpServerPort;
};
#endif // TCPCLIENT_H
二、TCP 服務器
● Qt 中使用 TCP 服務器通訊演示

● 實操流程圖

● 代碼
tcpserver.cpp
#include "tcpserver.h"
#include "ui_tcpserver.h"
#define TIMEMS qPrintable(QTime::currentTime().toString("HH:mm:ss zzz"))
TcpServer::TcpServer(QWidget *parent) :
QWidget(parent),
ui(new Ui::TcpServer)
{
ui->setupUi(this);
initForm();
}
TcpServer::~TcpServer()
{
delete ui;
}
//1. UI
//2. 初始化
// ① 創建QTcpSever物件
// ② 建立信號槽,有客戶端連接時,觸發newConnection信號,代表連接服務器成功
void TcpServer::initForm() {
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
}
//3. 偵聽埠,使得客戶端能用此埠訪問服務器 (server->listen)
void TcpServer::on_btnListen_clicked()
{
if (ui->btnListen->text() == "監聽") {
if (server->listen(QHostAddress::Any , 8888)) {
ui->txtMain->setTextColor(QColor("darkgreen"));
ui->btnListen->setText("關閉");
} else {
ui->txtMain->append("監聽失敗");
}
} else {
socket->abort();
server->close();
ui->btnListen->setText("監聽");
}
}
//4. 客戶端連接
// ① 連接成功觸發newConnection信號,
// ② 服務器通過socket 獲取客戶端連接資訊
// ③ 連接信號槽,接收到客戶端資料觸發
void TcpServer::newConnection()
{
//決議所有客戶連接
while (server->hasPendingConnections())
{
//連接上后通過socket獲取連接資訊
socket = server->nextPendingConnection();
QString str = QString("[ip:%1,port:%2]").arg(socket->peerAddress().toString()).arg(socket->peerPort());
//提示連接成功
ui->txtMain->append(str + " Connect to the server");
//復選框選項為連接服務器的ip
ui->cboxListenIP->addItem(str);
//監聽客戶端是否有訊息發送
connect(socket, &QTcpSocket::readyRead, this, &TcpServer::readData);
}
}
//5.1 接收客戶端資料 (socket->readAll())
void TcpServer::readData() {
QByteArray data = socket->readAll();
if (data.length() <= 0) return;
ui->txtMain->setTextColor(QColor("red"));
QString strData = "Receive: " + data;
ui->txtMain->append(strData);
}
//5.2 發送到客戶端資料 (socket->readAll())
void TcpServer::on_btnSend_clicked()
{
QString data = ui->cboxData->currentText();
if (data.length() <= 0) return;
QByteArray buffer = data.toUtf8();
socket->write(buffer);
QString strData = "Send: " + buffer;
ui->txtMain->setTextColor(QColor("darkgreen"));
ui->txtMain->append(strData);
}
tcpserver.h
#ifndef TCPSERVER_H
#define TCPSERVER_H
#include <QWidget>
#include <QtNetwork>
namespace Ui {
class TcpServer;
}
class TcpServer : public QWidget
{
Q_OBJECT
public:
explicit TcpServer(QWidget *parent = nullptr);
~TcpServer();
void initForm();
private:
Ui::TcpServer *ui;
QTcpServer *server;
QTcpSocket *socket;
private slots:
void newConnection();
void readData();
private slots:
void on_btnListen_clicked();
void on_btnSend_clicked();
};
#endif // TCPSERVER_H
原始碼: NetToolsTest
QT Widge 其它文章請點擊這里: QT Widget 學習筆記
姊妹篇:
Qt TCP/UDP 網路協議入門實操(一)TCP通訊
Qt TCP/UDP 網路協議入門實操(二)UDP通訊
Qt TCP/UDP 網路協議入門實操(補充)
參考:
飛揚青云——Qt撰寫網路除錯助手
QT從入門到入土(九)——TCP/IP網路通信(以及檔案傳輸)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323392.html
標籤:其他
