Basic functionality added to the Network class

This commit is contained in:
Denis Davydov 2018-06-15 17:12:41 +03:00
parent 2c5dca6f9f
commit 0ebdc434a1
2 changed files with 52 additions and 0 deletions

36
src/kernel/network.cpp Normal file
View File

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

16
src/kernel/network.hpp Normal file
View File

@ -0,0 +1,16 @@
#include "../lib/json/json.hpp"
#include <QtNetwork>
class Network
{
using json = nlohmann::json;
private:
QUdpSocket* udpSocket;
public:
Network();
public slots:
void sendDatagram();
private slots:
void readPendingDatagrams();
};