赞
踩
udp协议简单实现,自己发协议,自己接受
- QT = core
- QT += network
-
- CONFIG += c++17 cmdline
-
- # You can make your code fail to compile if it uses deprecated APIs.
- # In order to do so, uncomment the following line.
- #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
-
- SOURCES += \
- main.cpp \
- myudptest.cpp
-
- # Default rules for deployment.
- qnx: target.path = /tmp/$${TARGET}/bin
- else: unix:!android: target.path = /opt/$${TARGET}/bin
- !isEmpty(target.path): INSTALLS += target
-
- HEADERS += \
- myudptest.h
- #include <QCoreApplication>
- #include <QDebug>
- #include "myudptest.h"
-
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- qDebug()<<"hello udp";
- MyUdpTest* mudp = new MyUdpTest();
- mudp->write();
- return a.exec();
- }
- #ifndef MYUDPTEST_H
- #define MYUDPTEST_H
- //#include <QObject>
- #include <QUdpSocket>
-
- class MyUdpTest:public QObject
- {
- public:
- QUdpSocket *udpSocket;
- MyUdpTest();
- void readPendingDatagrams();
- void write();
- };
-
- #endif // MYUDPTEST_H
- #include "myudptest.h"
-
- MyUdpTest::MyUdpTest()
- {
- udpSocket = new QUdpSocket(this);
- udpSocket->bind(QHostAddress::Any, 5001);
-
- connect(udpSocket, &QUdpSocket::readyRead, this, &MyUdpTest::readPendingDatagrams);
- }
-
- void MyUdpTest::readPendingDatagrams(){
- while (udpSocket->hasPendingDatagrams()) {
- QByteArray datagram;
- datagram.resize(udpSocket->pendingDatagramSize());
- QHostAddress sender;
- quint16 senderPort;
- udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
- // 处理接收到的数据
- qDebug() << "Received datagram:" << QString::fromUtf8(datagram) << "from" << sender.toString() << ":" << senderPort;
- }
- }
-
- void MyUdpTest::write(){
- QHostAddress receiverAddress("192.168.1.106"); // 目标地址
- quint16 receiverPort = 5001; // 目标端口
- QString data = "Hello, UDP!";
- //QByteArray message = data.toUtf8();
- QByteArray message = "Hello, UDP!";
- udpSocket->writeDatagram(message, receiverAddress, receiverPort);
- }
hello udp
Received datagram: "Hello, UDP!" from "::ffff:192.168.1.106" : 5001
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。