Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

QByteArray

QDataStream

QUdpSocket

Code Block

 
Wiki Markup
QByteArray

QDataStream

QUdpSocket

\#include "sender.h"

SenderReceiver::SenderReceiver(QObject \*parent) :
       QObject(parent)
{
       sendUdpSocket = new QUdpSocket(0);
       receiveUdpSocket = new QUdpSocket(0);
       receiveUdpSocket->bind(45455,QUdpSocket::ShareAddress);
       connect(receiveUdpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
}

//viestien lahetys
void SenderReceiver::broadcastDatagram(QVector<float> v)
{
&nbsp;&nbsp;&nbsp;    int error,i;
&nbsp;&nbsp;&nbsp;    QByteArray datagram;
&nbsp;&nbsp;&nbsp;    qDebug() << v;
&nbsp;&nbsp;&nbsp;    QDataStream out (&datagram,QIODevice::WriteOnly);
&nbsp;&nbsp;&nbsp;    foreach(float f,v)
&nbsp;&nbsp;&nbsp;    {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;        out << f;
&nbsp;&nbsp;&nbsp;    }
&nbsp;&nbsp;&nbsp;    //kirjoitetaan udp-viesti, mahdollinen virhe kannattaisi tarkastaa
&nbsp;&nbsp;&nbsp;    error=sendUdpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 45455);
}

//viestien vastaanotto
void SenderReceiver::processPendingDatagrams()
{
&nbsp;&nbsp;&nbsp;    float f;
&nbsp;&nbsp;&nbsp;    //onko vastaanotettu viesteja
&nbsp;&nbsp;&nbsp;    while (receiveUdpSocket->hasPendingDatagrams()) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         QByteArray datagram;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         datagram.resize(receiveUdpSocket->pendingDatagramSize());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         receiveUdpSocket->readDatagram(datagram.data(), datagram.size());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         QDataStream in(datagram);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         while (\!in.atEnd()){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;             in >> f;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;             v2 << f;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         }
         qDebug() << v2;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         emit sendReceivedData(v2);
&nbsp;&nbsp;&nbsp;&nbsp;     }
}