網站首頁 編程語言 正文
TCP協議是經常使用的通信方式。在QT中做了非常友好的封裝,使用非常方便。
需要添加的模塊:network
Qt中的TCP類:QTcpSocket , QTcpServer
常用函數介紹
連接目標地址和端口
virtual void QTcpSocket ::connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite);
- 發送數據
inline qint64 QTcpSocket ::write(const QByteArray &data)
- 監聽某個地址和端口號
bool QTcpServer::listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
- 有新的連接信號
void QTcpServer::newConnection();
- 是否有新的連接
virtual bool QTcpServer::hasPendingConnections() const;
- 獲取新的連接,必須處理完才能繼續接收到連接
virtual QTcpSocket *QTcpServer::nextPendingConnection();
- 收到新的數據信號
void QTcpSocket::readyRead();
- 讀取收到的數據,必須讀取完才能繼續接收
QByteArray readAll();
使用案例(example)
客戶端
#include <QTcpSocket> #include <QWidget> #include <QLineEdit> class Client : public QWidget { ?? ?Q_OBJECT public: ?? ?Client(QWidget *parent); public slots: ?? ?void slotSendButtonClick(); private: ?? ?QTcpSocket *_socket; ?? ?QLineEdit *_lineEdit; ?? ?bool _isConnected; };
#include "client.h" #include <QPushButton> #include <QHBoxLayout> Client::Client(QWidget *parent) ?? ?: QWidget(parent) { ?? ?_socket = new QTcpSocket(this); ?? ?_lineEdit = new QLineEdit(this); ?? ?QPushButton *sendButton = new QPushButton("send"); ?? ?connect(sendButton, SIGNAL(clicked()), this, SLOT(slotSendButtonClick())); ?? ?connect(_lineEdit, SIGNAL(returnPressed()), this, SLOT(slotSendButtonClick())); ?? ? ?? ?QHBoxLayout *lay = new QHBoxLayout(this); ?? ?lay->addWidget(_lineEdit); ?? ?lay->addWidget(sendButton); ?? ?_isConnected = false; } void Client::slotSendButtonClick() { ?? ?if (!_isConnected) ?? ?{ ?? ??? ?_socket->connectToHost("127.0.0.1", 9988); ?? ??? ?_isConnected = true; ?? ?} ?? ?QString text = _lineEdit->text(); ?? ?if (!text.isEmpty()) ?? ?{ ?? ??? ?_socket->write(text.toUtf8());//發送數據 ?? ??? ?_lineEdit->clear(); ?? ?} }
服務端
#include <QWidget> #include <QTcpServer> #include <QTcpSocket> class QTextBrowser; class Server :public QWidget { ?? ?Q_OBJECT public: ?? ?Server(QWidget *parent); public slots: ?? ?void slotCurrentIndexChanged(const QString&); ?? ?void slotNewConnection(); private: ?? ?QTcpServer *_server; ?? ?QTcpSocket *_socket; ?? ?QTextBrowser *_textBrowser; };
#include "server.h" #include <QHostAddress> #include <QTextBrowser> #include <QByteArray> #include <QGridLayout> #include <QNetworkInterface> #include <QComboBox> Server::Server(QWidget *parent) { ?? ?_server = new QTcpServer(this); ?? ?//_server->listen(QHostAddress::Any, 9988);//監聽跟本主機相連的所有網口 ?? ?connect(_server, SIGNAL(newConnection()),this, SLOT(slotNewConnection()) ); ?? ?QList<QHostAddress> addrList = QNetworkInterface::allAddresses(); ?? ?QComboBox *comboBox = new QComboBox; ?? ?for (const QHostAddress& addr : addrList) ?? ?{ ?? ??? ?quint32 ipAddr = addr.toIPv4Address(); ?? ??? ?if (ipAddr != 0) ?? ??? ?{ ?? ??? ??? ?comboBox->addItem(QHostAddress(ipAddr).toString()); ?? ??? ?} ?? ?} ?? ?connect(comboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(slotCurrentIndexChanged(const QString&))); ?? ?_textBrowser = new QTextBrowser(this); ?? ?QGridLayout *lay = new QGridLayout(this); ?? ?lay->addWidget(comboBox, 0, 0); ?? ?lay->addWidget(_textBrowser,1,0); } void Server::slotCurrentIndexChanged(const QString& item) { ?? ?if (!_server->isListening()) ?? ?{ ?? ??? ?_server->listen(QHostAddress(item), 9988); ?? ?} ?? ? ?? ?_textBrowser->append("listen..."); } void Server::slotNewConnection() { ?? ?_textBrowser->append("connecting..."); ?? ?while (_server->hasPendingConnections())//必須處理完所有的連接,否則有新連接時就不會在發信號過來 ?? ?{ ?? ??? ?_socket = _server->nextPendingConnection(); ?? ??? ?connect(_socket, &QTcpSocket::readyRead, [&]() { ?? ??? ??? ?_textBrowser->append("receive message..."); ?? ??? ??? ?QByteArray newMessage = _socket->readAll(); ?? ??? ??? ?_textBrowser->append(QString(newMessage)); ?? ??? ?}); ?? ?} }
使用效果
原文鏈接:https://blog.csdn.net/geduo_feng/article/details/103102856
相關推薦
- 2022-06-01 C語言線性表中順序表超詳細理解_C 語言
- 2022-07-30 Redis實現訂單過期刪除的方法步驟_Redis
- 2022-04-12 Python數據可視化Pyecharts庫的使用教程_python
- 2022-10-16 Python計算標準差之numpy.std和torch.std的區別_python
- 2023-12-02 nginx環境配置首頁可以訪問,路由頁面都404報錯
- 2022-12-09 python返回多個值與賦值多個值的示例代碼_python
- 2022-11-18 Python?ndarray?數組的變形詳情_python
- 2022-09-05 C語言之實現單鏈表指定結點的插入方式_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支