KanoopCommonQt 2.1.1
Kanoop foundational Qt utility library
Loading...
Searching...
No Matches
udpserver.h
1/**
2 * @brief A UDP server that receives datagrams and queues outgoing datagrams.
3 */
4#ifndef UDPSERVER_H
5#define UDPSERVER_H
6
7#include <QList>
8#include <QUdpSocket>
9#include <QNetworkDatagram>
10
11#include <Kanoop/utility/abstractthreadclass.h>
12
13/**
14 * @brief Receives and transmits UDP datagrams in a dedicated thread.
15 *
16 * UdpServer binds to the configured address and port on start(). Incoming
17 * datagrams are delivered via the datagramReceived() signal. Outgoing datagrams
18 * are queued and sent asynchronously via writeDatagram().
19 */
20class KANOOP_EXPORT UdpServer : public AbstractThreadClass
21{
22 Q_OBJECT
23public:
24 /**
25 * @brief Construct a UdpServer bound to the given address and port.
26 * @param serverAddress Address to bind to
27 * @param serverPort Port to bind to
28 */
29 UdpServer(const QHostAddress& serverAddress, int serverPort);
30
31 /**
32 * @brief Queue a datagram for transmission to the specified address and port.
33 * @param datagram Payload bytes to send
34 * @param address Destination address
35 * @param port Destination port
36 */
37 void writeDatagram(const QByteArray& datagram, const QHostAddress& address, int port);
38
39 /**
40 * @brief Queue a fully-specified datagram for transmission.
41 * @param datagram QNetworkDatagram including destination address and port
42 */
43 void writeDatagram(const QNetworkDatagram& datagram);
44
45private:
46 /** @brief Bind the UDP socket when the thread starts. */
47 virtual void threadStarted() override;
48
49 QHostAddress _serverAddress;
50 int _serverPort;
51
52 QUdpSocket* _socket;
53
54 QList<QNetworkDatagram> _transmitQueue;
55 QMutex _queueLock;
56
57signals:
58 /**
59 * @brief Emitted when a datagram is received.
60 * @param datagram The received datagram including sender address and port
61 */
62 void datagramReceived(const QNetworkDatagram& datagram);
63
64private slots:
65 /** @brief Called when incoming datagrams are available to read. */
66 void readPendingDatagrams();
67 /** @brief Called to drain and send the outgoing transmit queue. */
68 void serviceTransmitQueue();
69};
70
71#endif // UDPSERVER_H
Abstract base class for QObject-based workers that run in a dedicated QThread.
virtual void threadStarted()=0
Entry point called on the worker thread immediately after it starts.
A UDP server that receives datagrams and queues outgoing datagrams.
Definition udpserver.h:21
UdpServer(const QHostAddress &serverAddress, int serverPort)
Construct a UdpServer bound to the given address and port.
void writeDatagram(const QNetworkDatagram &datagram)
Queue a fully-specified datagram for transmission.
void writeDatagram(const QByteArray &datagram, const QHostAddress &address, int port)
Queue a datagram for transmission to the specified address and port.
void datagramReceived(const QNetworkDatagram &datagram)
Emitted when a datagram is received.