QByteArray
QDataStream
QUdpSocket
esimerkki zipattuna BroadcastServer.zip
#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) { int error,i; QByteArray datagram; qDebug() << v; QDataStream out (&datagram,QIODevice::WriteOnly); foreach(float f,v) { out << f; } //kirjoitetaan udp-viesti, mahdollinen virhe kannattaisi tarkastaa error=sendUdpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 45455); } //viestien vastaanotto void SenderReceiver::processPendingDatagrams() { float f; //onko vastaanotettu viesteja while (receiveUdpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(receiveUdpSocket->pendingDatagramSize()); receiveUdpSocket->readDatagram(datagram.data(), datagram.size()); QDataStream in(datagram); while (!in.atEnd()){ in >> f; v2 << f; } qDebug() << v2; emit sendReceivedData(v2); } }
#ifndef SENDER_H #define SENDER_H #include <QObject> #include <QUdpSocket> class SenderReceiver : public QObject { Q_OBJECT public: explicit SenderReceiver(QObject *parent = 0); QUdpSocket *sendUdpSocket; QUdpSocket *receiveUdpSocket; void broadcastDatagram(QVector<float> v); void testia(); QVector<float> v2; signals: void sendReceivedData(QVector<float> v2); public slots: //viestejä vastaanottava slot void processPendingDatagrams(); }; #endif // SENDER_H
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(&sender,SIGNAL(sendReceivedData(QVector<float>)),this,SLOT(dataReceivedSlot(QVector<float>))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pBSend_clicked() { QVector <float> v1; v1.append(ui->lE_Send->text().toFloat()); v1.append(ui->lE_Send_2->text().toFloat()); v1.append(ui->lE_Send_3->text().toFloat()); sender.broadcastDatagram(v1); } void MainWindow::dataReceivedSlot(QVector<float> v2) { int i; float ftmp; QString tmp=""; QString tmp2=""; int koko=v2.size(); for(i=0;i<koko;i++){ ftmp=v2.at(i); tmp.setNum(ftmp); tmp2+=tmp; tmp2+=" "; } ui->lE_Receive->setText(tmp2); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "sender.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); SenderReceiver sender; private slots: void on_pBSend_clicked(); private: Ui::MainWindow *ui; public slots: void dataReceivedSlot(QVector<float> v2); }; #endif // MAINWINDOW_H