QT 網絡編程 8

1 基礎知識

udp?

?

tcp?

2 UDP

框架

客戶端:
QUdpSocket x;
qint64 writeDatagram(
const char *data,
qint64 size, 
const QHostAddress &address, 
quint16 port
);服務器:
void Server::initSocket(){udpSocket = new QUdpSocket(this);udpSocket->bind(QHostAddress::LocalHost, 7755);connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));}

2.1 客戶端示例:

網絡編程都需添加network(后面不再提醒)

widget.h?

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QUdpSocket>
#include <QHostAddress>class Widget : public QWidget
{Q_OBJECT
public slots:void senddata(){udpsock->writeDatagram(le->text().toStdString().c_str(), QHostAddress("192.168.31.124"), 8888);}void recvdata(){QByteArray datagram;datagram.resize(udpsock->pendingDatagramSize());QHostAddress sender;quint16 senderPort;udpsock->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);te->append(datagram);}
public:Widget(QWidget *parent = 0);~Widget();
private:QTextEdit *te;QLineEdit *le;QPushButton *pb;QUdpSocket *udpsock;
};#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include <QVBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent)
{te = new QTextEdit;le = new QLineEdit;pb = new QPushButton("send");QVBoxLayout *vbox = new QVBoxLayout;vbox->addWidget(te);vbox->addWidget(le);vbox->addWidget(pb);setLayout(vbox);udpsock = new QUdpSocket;connect(pb, SIGNAL(clicked(bool)), this, SLOT(senddata()));connect(udpsock, SIGNAL(readyRead()), this, SLOT(recvdata()));
}Widget::~Widget()
{}

2.2 服務端

添加network

udpserver.h

#ifndef UDPSERVER_H // 如果UDPSERVER_H沒有被定義
#define UDPSERVER_H // 定義UDPSERVER_H#include <QObject> // 包含QObject的頭文件,QObject是所有Qt對象的基類
#include <QUdpSocket> // 包含QUdpSocket的頭文件,用于UDP通信
#include <QDebug> // 包含QDebug的頭文件,用于在調試時輸出信息// 聲明udpServer類,繼承自QObject
class udpServer : public QObject
{Q_OBJECT // 啟用Qt的信號和槽機制
public:explicit udpServer(QObject *parent = 0); // 構造函數,explicit防止隱式轉換,可選的parent參數默認為0void init() // 初始化函數{udpSocket = new QUdpSocket(this); // 創建QUdpSocket對象udpSocket->bind(QHostAddress::AnyIPv4, 8888); // 綁定到任意IPv4地址的8888端口// 連接QUdpSocket的readyRead信號到本類的readPendingDatagrams槽,當有數據可讀時觸發connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));qDebug()<<"init...."; // 使用QDebug輸出初始化信息}
signals: // 信號部分,此處未定義任何信號public slots: // 槽部分void readPendingDatagrams() // 當有數據待讀取時,會調用此函數{while (udpSocket->hasPendingDatagrams()) { // 循環處理所有待讀取的數據報QByteArray datagram; // 用于存儲接收到的數據報datagram.resize(udpSocket->pendingDatagramSize()); // 調整大小以匹配待讀取數據報的大小QHostAddress sender; // 發送者的地址quint16 senderPort; // 發送者的端口// 讀取數據報,并保存發送者的地址和端口udpSocket->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);//processTheDatagram(datagram); // 處理數據報的函數qDebug()<<"recv: "<<datagram; // 使用QDebug輸出接收到的數據報// 將接收到的數據報原樣發送回去udpSocket->writeDatagram(datagram.data(), datagram.size(),sender, senderPort);}}private:QUdpSocket *udpSocket; // 指向QUdpSocket對象的指針
};#endif // UDPSERVER_H // 結束預處理器指令

udpserver.cpp

#include "udpserver.h"udpServer::udpServer(QObject *parent) : QObject(parent)
{}

main.cpp

#include <QCoreApplication>
#include <udpserver.h>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);udpServer server;server.init();return a.exec();
}

最終效果:

3 TCP

框架

客戶端:
mytcpsock = new QTcpSocket;
Mytcpsock->connectToHost(
QHostAddress("192.168.4.222"), 8888);connect(mytcpsock, SIGNAL(readyRead()), this, SLOT(read_data()));服務器:
Server::Server(QObject *parent) : QObject(parent)
{tcpserver = new QTcpServer;tcpserver->listen(QHostAddress::AnyIPv4, 8888);connect(tcpserver, SIGNAL(newConnection()),this, SLOT(new_client()));tcpserver->waitForNewConnection();
}

3.1 客戶端

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QTcpSocket>class Widget : public QWidget
{Q_OBJECT
public slots:void senddata(){tcpsocket->write(le->text().toStdString().c_str());}void recvdata(){QByteArray buf = tcpsocket->readAll();te->append(buf);}public:Widget(QWidget *parent = 0);~Widget();
private:QLineEdit *le;QPushButton *pb;QTextEdit *te;QTcpSocket *tcpsocket;
};#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include <QVBoxLayout>
#include <QHostAddress>Widget::Widget(QWidget *parent): QWidget(parent)
{le = new QLineEdit;pb = new QPushButton("senddata");te = new QTextEdit;QVBoxLayout *vbox = new QVBoxLayout;vbox->addWidget(te);vbox->addWidget(le);vbox->addWidget(pb);setLayout(vbox);tcpsocket = new QTcpSocket;//connect to servertcpsocket->connectToHost(QHostAddress("192.168.1.155"), 8888);connect(pb, SIGNAL(clicked(bool)), this, SLOT(senddata()));connect(tcpsocket, SIGNAL(readRead()), this, SLOT(recvdata()));}Widget::~Widget()
{}

main.cpp

#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}

3.2 服務端

tcpServer.h

#ifndef TCPSERVER_H
#define TCPSERVER_H#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QDebug>class TcpServer : public QObject
{Q_OBJECT // 啟用Qt的信號和槽機制
public:explicit TcpServer(QObject *parent = 0);
public slots:void newConnected(){qDebug() << "connected";clientsock = ser->nextPendingConnection(); //得到客戶端connect(clientsock, SIGNAL(readyRead()), this, SLOT(recvData()));}void recvData(){QByteArray buf = clientsock->readAll();qDebug()<<"recv:"<<buf;clientsock->write(buf);}private:QTcpServer *ser;QTcpSocket *clientsock;};#endif // TCPSERVER_H

tcpServer.cpp

#include "tcpServer.h"TcpServer::TcpServer(QObject *parent) : QObject(parent)
{ser = new QTcpServer;ser->listen(QHostAddress::AnyIPv4, 8888);  //監聽端口connect(ser, SIGNAL(newConnection()), this, SLOT(newConnected()));  //當新客戶端來了與槽函數newConnected掛接上ser->waitForNewConnection(); //開啟監聽}

?main.cpp

#include <QCoreApplication>
#include "tcpserver.h"
int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);TcpServer server;return a.exec();
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/716598.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/716598.shtml
英文地址,請注明出處:http://en.pswp.cn/news/716598.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

macos jupyter notebook字體的修改

終端codemirror 記事本打開 搜索font-family 修改font-size保存即可

重學SpringBoot3-@ConditionalOnXxx條件注解

重學SpringBoot3-ConditionalOnXxx條件注解 引言常見的條件注解常見的條件注解示例擴展條件注解1. ConditionalOnJndi2. ConditionalOnJava3. ConditionalOnCloudPlatform4. ConditionalOnEnabledResourceChain5. 自定義條件注解 總結 引言 Spring Boot 提供了一組強大的條件注…

ERDAS監督分類與溫度反演教程

本期帶來監督分類教程&#xff0c;更多內容&#xff0c;歡迎關注小編的公眾號梧桐涼月哦&#xff01;&#xff01;&#xff01; 一、研究區自然、地理環境特征&#xff1a; 1、景德鎮市位于中國江西省東北部&#xff0c;地處贛江中游的贛北盆地&#xff0c;地形地貌以丘陵和低…

mitmproxy代理

文章目錄 mitmproxy1. 網絡代理2. 安裝3. Https請求3.1 啟動mitmproxy3.2 獲取證書3.3 配置代理3.4 運行測試 4. 請求4.1 讀取請求4.2 修改請求4.3 攔截請求 5. 響應5.1 讀取響應5.2 修改響應 6. 案例&#xff1a;共享賬號6.1 登錄bilibili獲取cookies6.2 在代理請求中設置cook…

ER-NeRF實時對話數字人模型訓練與部署

ER-NeRF是基于NeRF用于生成數字人的方法&#xff0c;可以達到實時生成的效果。 下載源碼 cd D:\Projects\ git clone https://github.com/Fictionarry/ER-NeRF cd D:\Projects\ER-NeRF 下載模型 準備面部解析模型 wget https://github.com/YudongGuo/AD-NeRF/blob/master/…

MyBatisPlus入門教程

MyBatisPlus MyBatis-Plus (opens new window)&#xff08;簡稱 MP&#xff09;是一個 MyBatis (opens new window) 的增強工具&#xff0c;在 MyBatis 的基礎上只做增強不做改變&#xff0c;為簡化開發、提高效率而生。 官網地址&#xff1a;https://baomidou.com/ 一、入門案…

sql注入之sqli-labs-less-1 錯誤注入

輸入?id1 得到登錄頁面&#xff1a; 通過order by 函數試探&#xff1a; 5的時候報錯 試探到3 的時候返回正確的值&#xff1a; 然后繼續注入&#xff1a;?id -1 union select 1,2,3 -- 查看回顯點&#xff1a; 開始查看數據庫內容&#xff1a;id-1 union select 1,databa…

OpenXR 超詳細的spec--API初始化介紹

3.API 初始化 3.2 Function Pointers XrResult xrGetInstanceProcAddr(XrInstance instance,const char* name,PFN_xrVoidFunction* function); instance: XrInstance類型&#…

open-spider開源爬蟲工具:抖音數據采集

在當今信息爆炸的時代&#xff0c;網絡爬蟲作為一種自動化的數據收集工具&#xff0c;其重要性不言而喻。它能夠幫助我們從互聯網上高效地提取和處理數據&#xff0c;為數據分析、市場研究、內容監控等領域提供支持。抖音作為一個全球性的短視頻平臺&#xff0c;擁有海量的用戶…

CKA考生注意:這些Deployment要點能助你一臂之力!

往期精彩文章 : 提升CKA考試勝算&#xff1a;一文帶你全面了解RBAC權限控制&#xff01;揭秘高效運維&#xff1a;如何用kubectl top命令實時監控K8s資源使用情況&#xff1f;CKA認證必備&#xff1a;掌握k8s網絡策略的關鍵要點提高CKA認證成功率&#xff0c;CKA真題中的節點維…

68-解構賦值,迭代器,生成器函數

1.解構賦值(針對數組array&#xff0c;字符串String及對象object以) 結構賦值是一種特殊的語法&#xff0c;通過將各種結構中的元素復制到變量中達到"解構"的目的&#xff0c;但是數組本身沒有改變 1.1解構單層數組 <script>let arr [1,2,3,4,5];//獲取數組…

c++ primer學習筆記(一)

目錄 第一章、c快速入門 重點&#xff1a;類的簡介 第二章 1、基本內置類型 2、字面值常量 1、整型字面值規則 2、浮點字面值規則 3、布爾字面值 4、字符字面值 5、非打印字符的轉義序列 ?編輯 6、字符串字面值 3、變量 1、變量標識符 2、定義和初始化對象 3、…

leetcode 1328.破壞回文串

題目鏈接LeetCode1328 1.題目 給你一個由小寫英文字母組成的回文字符串 palindrome &#xff0c;請你將其中 一個 字符用任意小寫英文字母替換&#xff0c;使得結果字符串的 字典序最小 &#xff0c;且 不是 回文串。 請你返回結果字符串。如果無法做到&#xff0c;則返回一個…

java: 無法訪問org.springframework.web.bind.annotation.RequestMapping......類文件具有錯誤的版本 61.0, 應為 52.0

文章目錄 一、報錯問題二、問題背景三、原因分析四、解決方案 一、報錯問題 java: 無法訪問org.springframework.web.bind.annotation.RequestMapping 錯誤的類文件: /D:/SoftwareInstall/Maven/repository/org/springframework/spring-web/6.0.9/spring-web-6.0.9.jar!/org/s…

latex報錯Repeated entry解決辦法

報錯原因——重復了兩個參考文獻&#xff0c;刪掉一個即可 總結 "Repeated entry"這個錯誤通常出現在你嘗試在LaTeX中多次使用同一個標簽&#xff08;label&#xff09;或者多次插入相同的圖像/表格等時。例如&#xff0c;在LaTeX中&#xff0c;我們可能會為每一個章…

Modern C++ std::any為何要求Tp可拷貝構造?

小問題也會影響設計的思路&#xff0c;某個問題或某種case的探討有助于理解設計的初衷。 聲明&#xff1a;以下_Tp/Tp都是指要放入std::any的對象的類型。 它要求_Tp is_copy_constructible, 僅僅是因為有很多函數的實現調用了Tp的拷貝構造函數嗎&#xff1f;比如說上節提到的初…

動態SQL的處理

學習視頻&#xff1a;3001 動態SQL中的元素_嗶哩嗶哩_bilibili 目錄 1.1為什么學 1.2動態SQL中的元素 條件查詢操作 if 元素 choose、when、otherwise元素 where、trim元素 更新操作 set元素使用場景 復雜查詢操作 foreach 元素中的屬性 ?編輯 迭代數組 迭代List 迭代Map 1…

代碼隨想錄算法訓練營第二十七天|LeetCode93 復原IP地址、LeetCode78 子集、LeetCode90 子集II

93.復原IP地址 思路&#xff1a;要建立一個判斷子字符串是否合法的函數&#xff0c;判斷多種不合法的情況。在回溯函數中&#xff0c;參數除了s,和startindex還需要一個pointNum來記錄句點的數量&#xff0c;當句點的數量等于3時&#xff0c;判斷最后一個子串是否合法&#xf…

第3部分 原理篇2去中心化數字身份標識符(DID)(4)

3.2.3. DID解析 3.2.3.1. DID解析參與方 圖3-5 DID 解析過程 本聰老師&#xff1a;我們之前提到過&#xff0c;DID 解析過程是將 DID 轉換為對應的 DID 文檔。這樣做的目的是驗證 DID 所代表的主體的身份。那么解析過程會涉及哪些概念呢&#xff1f;我們看圖3-&#xff0c;DI…

端智能:面向手機計算環境的端云協同AI技術創新

近年來&#xff0c;隨著移動端設備軟硬件能力的進步&#xff0c;移動端的算力有了很大提升&#xff0c;同時面向移動端的機器學習框架和模型輕量化技術越來越成熟&#xff0c;端上的AI能力逐漸進入大眾視野&#xff0c;端智能在電商領域也開始逐步走向規模化應用。通過持續探索…