Example UDP server project

This commit is contained in:
Ollo 2023-08-13 22:38:07 +02:00
parent 1c3c64f447
commit 3aace88c0b
3 changed files with 62 additions and 2 deletions

View File

@ -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

View File

@ -0,0 +1,35 @@
#include "udpserver.h"
#include <QUdpSocket>
#include <QNetworkDatagram>
#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();
}
}

View File

@ -0,0 +1,22 @@
#ifndef UDPSERVER_H
#define UDPSERVER_H
#include <QAbstractItemModel>
#include <QUdpSocket>
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