赞
踩
#include <QTcpSocket> #include <QUdpSocket> class NetworkHelper : public QObject { Q_OBJECT public: NetworkHelper(QObject* parent = nullptr) : QObject(parent) {} public slots: void tcpConnect(QString host, int port) { tcpSocket = new QTcpSocket(this); connect(tcpSocket, SIGNAL(connected()), this, SLOT(onConnected())); connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(onTcpReadyRead())); tcpSocket->connectToHost(host, port); } void udpBind(int port) { udpSocket = new QUdpSocket(this); connect(udpSocket, SIGNAL(readyRead()), this, SLOT(onUdpReadyRead())); if (udpSocket->bind(QHostAddress::Any, port)) { qDebug() << "UDP socket bound to port " << port; } else { qWarning() << "Failed to bind UDP socket to port " << port << ": " << udpSocket->errorString(); } } void sendTcp(QString message) { if (tcpSocket) { tcpSocket->write(message.toUtf8()); } } void sendUdp(QString message, QString host, int port) { if (udpSocket) { udpSocket->writeDatagram(message.toUtf8(), QHostAddress(host), port); } } signals: void connected(); void tcpMessageReceived(QString message); void udpMessageReceived(QString message, QString host, int port); private slots: void onConnected() { qDebug() << "Connected to TCP server"; emit connected(); } void onTcpReadyRead() { while (tcpSocket->canReadLine()) { QString message = QString::fromUtf8(tcpSocket->readLine()).trimmed(); qDebug() << "TCP message received: " << message; emit tcpMessageReceived(message); } } void onUdpReadyRead() { while (udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); QString message = QString::fromUtf8(datagram).trimmed(); qDebug() << "UDP message received from " << sender.toString() << ":" << senderPort << ": " << message; emit udpMessageReceived(message, sender.toString(), senderPort); } } private: QTcpSocket* tcpSocket = nullptr; QUdpSocket* udpSocket = nullptr; };
使用该类可以完成以下操作:
通过tcpConnect(QString host, int port)
函数建立与TCP服务器的连接;
通过udpBind(int port)
函数绑定UDP端口;
通过sendTcp(QString message)
函数向TCP服务器发送消息;
通过sendUdp(QString message, QString host, int port)
函数向指定主机和端口发送UDP消息;
监听TCP和UDP通信并在收到消息时发出相应的信号:connected()
(TCP连接成功)、tcpMessageReceived(QString message)
(收到TCP消息)、udpMessageReceived(QString message, QString host, int port)
(收到UDP消息)。
示例代码只是一个简单的实现,可能存在一些不足之处,具体实现还需要根据项目需求进行完善。
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。