用qt写一个udp收发的自定义报文协议
时间: 2023-09-06 19:12:17 浏览: 155
基于QT的UDP广播程序报文
5星 · 资源好评率100%
下面是一个用 Qt 写的 UDP 收发自定义报文协议的示例代码:
```cpp
#include <QtNetwork/QUdpSocket>
struct MyPacket {
quint16 id;
quint8 type;
QByteArray data;
};
class MyUdpProtocol : public QObject {
Q_OBJECT
public:
explicit MyUdpProtocol(QObject *parent = nullptr)
: QObject(parent), socket(new QUdpSocket(this))
{
connect(socket, &QUdpSocket::readyRead, this, &MyUdpProtocol::onReadyRead);
}
bool bind(quint16 port)
{
return socket->bind(QHostAddress::Any, port);
}
void sendPacket(const MyPacket &packet, const QHostAddress &address, quint16 port)
{
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out << packet.id << packet.type << packet.data;
socket->writeDatagram(datagram, address, port);
}
signals:
void packetReceived(const MyPacket &packet, const QHostAddress &sender, quint16 senderPort);
private slots:
void onReadyRead()
{
while (socket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
if (socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort) == -1) {
continue;
}
QDataStream in(datagram);
MyPacket packet;
in >> packet.id >> packet.type >> packet.data;
emit packetReceived(packet, sender, senderPort);
}
}
private:
QUdpSocket *socket;
};
```
你可以根据自己的需求修改 `MyPacket` 的成员变量,然后在 `sendPacket` 和 `packetReceived` 中处理自定义的报文协议。使用方法示例:
```cpp
MyUdpProtocol protocol;
protocol.bind(1234);
connect(&protocol, &MyUdpProtocol::packetReceived, [](const MyPacket &packet, const QHostAddress &sender, quint16 senderPort) {
qDebug() << "Received packet from" << sender.toString() << senderPort << ": ID=" << packet.id << ", Type=" << packet.type << ", Data=" << packet.data;
});
MyPacket packet = { 1234, 1, QByteArray("Hello, World!") };
protocol.sendPacket(packet, QHostAddress::LocalHost, 1234);
```
阅读全文