From 0ebdc434a15c19a41fb973c839c480ab2ac77bce Mon Sep 17 00:00:00 2001 From: Denis Davydov Date: Fri, 15 Jun 2018 17:12:41 +0300 Subject: [PATCH] Basic functionality added to the Network class --- src/kernel/network.cpp | 36 ++++++++++++++++++++++++++++++++++++ src/kernel/network.hpp | 16 ++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/kernel/network.cpp create mode 100644 src/kernel/network.hpp diff --git a/src/kernel/network.cpp b/src/kernel/network.cpp new file mode 100644 index 0000000..321e1bc --- /dev/null +++ b/src/kernel/network.cpp @@ -0,0 +1,36 @@ +Network::Network() +{ + udpSocket = new QUdpSocket(this); + udpSocket->bind(QHostAddress::AnyIPv6, 6552); + connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); +} +void Network::readPendingDatagrams() +{ + while (udpSocket->hasPendingDatagrams()) { + QNetworkDatagram datagram = udpSocket->receiveDatagram(); + processTheDatagram(datagram); + } +} +void Network::sendDatagram(json *j, QHostAddress ip) +{ + QByteArray baDatagram; + QDataStream out(&baDatagram, QIODevice::WriteOnly); + QString s = j.dump(); + out << s; + udpSocket->writeDatagram(baDatagram, ip, 6552); +} +json Network::processTheDatagram() +{ + QByteArray baDatagram; + do { + baDatagram.resize(udpSocket->pendingDatagramSize ()) ; + udpSocket->readDatagram (baDatagram.data(), baDatagram.size()) ; + } while (udpSocket->hasPendingDatagrams()) ; + + QString buff; + QDataStream in(&baDatagram, QIODevice::Readonly); + in >> buff; + json j = new json; + j = json::parse(buff); + return json; +} diff --git a/src/kernel/network.hpp b/src/kernel/network.hpp new file mode 100644 index 0000000..12b1121 --- /dev/null +++ b/src/kernel/network.hpp @@ -0,0 +1,16 @@ +#include "../lib/json/json.hpp" +#include + +class Network +{ + using json = nlohmann::json; + + private: + QUdpSocket* udpSocket; + public: + Network(); + public slots: + void sendDatagram(); + private slots: + void readPendingDatagrams(); +};