From 3aace88c0b92ba2a899f7853b84d00f060071439 Mon Sep 17 00:00:00 2001 From: Ollo Date: Sun, 13 Aug 2023 22:38:07 +0200 Subject: [PATCH] Example UDP server project --- .../VirtualLedBoard/VirtualLedBoard.pro | 7 ++-- simulation/VirtualLedBoard/udpserver.cpp | 35 +++++++++++++++++++ simulation/VirtualLedBoard/udpserver.h | 22 ++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 simulation/VirtualLedBoard/udpserver.cpp create mode 100644 simulation/VirtualLedBoard/udpserver.h diff --git a/simulation/VirtualLedBoard/VirtualLedBoard.pro b/simulation/VirtualLedBoard/VirtualLedBoard.pro index e403327..4ba635f 100644 --- a/simulation/VirtualLedBoard/VirtualLedBoard.pro +++ b/simulation/VirtualLedBoard/VirtualLedBoard.pro @@ -1,4 +1,5 @@ QT += core gui +QT += network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets @@ -10,10 +11,12 @@ CONFIG += c++11 SOURCES += \ main.cpp \ - mainwindow.cpp + mainwindow.cpp \ + udpserver.cpp HEADERS += \ - mainwindow.h + mainwindow.h \ + udpserver.h FORMS += \ mainwindow.ui diff --git a/simulation/VirtualLedBoard/udpserver.cpp b/simulation/VirtualLedBoard/udpserver.cpp new file mode 100644 index 0000000..b884803 --- /dev/null +++ b/simulation/VirtualLedBoard/udpserver.cpp @@ -0,0 +1,35 @@ +#include "udpserver.h" +#include +#include + +#define UDP_IMAGE_PORT 4242 + +UdpServer::UdpServer(QObject *parent) + : QAbstractItemModel(parent) +{ + initSocket(); +} + +void UdpServer::initSocket() +{ + this->mUdpSocket = new QUdpSocket(this); + this->mUdpSocket->bind(QHostAddress::LocalHost, UDP_IMAGE_PORT); + + connect(this->mUdpSocket, &QUdpSocket::readyRead, + this, &UdpServer::readPendingDatagrams); +} + + +void UdpServer::readPendingDatagrams() +{ + while (this->mUdpSocket->hasPendingDatagrams()) { + QNetworkDatagram datagram = this->mUdpSocket->receiveDatagram(); + processTheDatagram(datagram); + } +} + +void UdpServer::processTheDatagram(QNetworkDatagram datagram) { + if (datagram.isValid()) { + qDebug() << "Received datagram:" << datagram.data().size(); + } +} diff --git a/simulation/VirtualLedBoard/udpserver.h b/simulation/VirtualLedBoard/udpserver.h new file mode 100644 index 0000000..8c91894 --- /dev/null +++ b/simulation/VirtualLedBoard/udpserver.h @@ -0,0 +1,22 @@ +#ifndef UDPSERVER_H +#define UDPSERVER_H + +#include +#include + +class UdpServer : public QAbstractItemModel +{ + Q_OBJECT + +public: + explicit UdpServer(QObject *parent = nullptr); + + +private: + void initSocket(); + void readPendingDatagrams(); + QUdpSocket *mUdpSocket; + void processTheDatagram(QNetworkDatagram datagram); +}; + +#endif // UDPSERVER_H