增加组播组件接收功能

This commit is contained in:
hehaoyang 2024-01-12 18:43:14 +08:00
parent ffa89d0bef
commit 46e7e79987
3 changed files with 95 additions and 54 deletions

1
.gitignore vendored
View File

@ -6,3 +6,4 @@ Makefile*
*.Debug
*.Release
*.TMP
._*

View File

@ -2,16 +2,43 @@
#include <QHostAddress>
int HxBroadcast::port = 0;
QUdpSocket *HxBroadcast::socket = nullptr;
HxBroadcast *broadcast = nullptr;
HxBroadcast* HxBroadcast::context() { return broadcast; }
void HxBroadcast::initialization(int port)
{
HxBroadcast::port = port;
HxBroadcast::socket = new QUdpSocket();
broadcast = new HxBroadcast();
broadcast->port = port;
broadcast->socket = new QUdpSocket();
connect(broadcast->socket, &QUdpSocket::readyRead, broadcast, &HxBroadcast::receive_ready_read);
connect(broadcast, &HxBroadcast::publish_event, broadcast, &HxBroadcast::publish_achieve);
}
void HxBroadcast::publish(QString message)
{
socket->writeDatagram(message.toUtf8(), QHostAddress::Broadcast, port);
emit broadcast->publish_event(message);
}
void HxBroadcast::publish_achieve(QString message)
{
socket->writeDatagram(message.toUtf8(), QHostAddress::Broadcast, broadcast->port);
}
void HxBroadcast::receive_ready_read()
{
/* 拥有等待的数据报 */
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
/* 让datagram的大小为等待处理的数据报的大小这样才能接收到完整的数据 */
datagram.resize(socket->pendingDatagramSize());
/* 接收数据报将其存放到datagram中*/
socket->readDatagram(datagram.data(), datagram.size());
emit broadcast->receive_event(QString::fromLocal8Bit(datagram));
}
}

View File

@ -4,9 +4,12 @@
#include <QObject>
#include <QUdpSocket>
class HxBroadcast
class HxBroadcast : public QObject
{
Q_OBJECT
public:
static HxBroadcast* context();
/**
* @brief
*
@ -22,8 +25,18 @@ public:
static void publish(QString message);
private:
static int port;
static QUdpSocket *socket;
void publish_achieve(QString message);
signals:
void publish_event(QString message);
void receive_event(QString data);
private slots:
void receive_ready_read();
private:
int port;
QUdpSocket *socket;
};
#endif // HXBROADCAST_H