#ifndef GATEWAY_H#define GATEWAY_H#include <QObject>#include <QThread>#include <QList>#include <QtNetwork/QUdpSocket>#include <QtNetwork/QHostAddress>////////////////////////////////////////////////////////////////////////class Gateway : public QObject, public QThread{ Q_OBJECTpublic: explicit Gateway(QObject *parent = 0); virtual void addRecipient(Gateway*)=0;signals: public slots: virtual void readMessage()=0; virtual void sendMessage(QByteArray*)=0;protected: QList<Gateway> listRecipients;};////////////////////////////////////////////////////////////////////////class GatewayUdp : public QObject,public Gateway{ Q_OBJECTpublic: GatewayUdp(QString,int,int,QObject *parent=0); void addRecipient(Gateway*); void run();public slots: void readMessage(); void sandMessage(QByteArray*); //void setData(QString,int,int);private: QUdpSocket *udpSocket; QHostAddress fromAdr; //Адрес отправителя quint16 fromPort; //Порт отправителя. Порт который слушаем. quint16 inPort; //Порт по которому отправляем сообщения.};#endif // GATEWAY_H
#include "gateway.h"Gateway::Gateway(QObject *parent) : QObject(parent){}/////////////////////////////////////////////////////////////////////////////////////////////////GatewayUdp::GatewayUdp(QString fromAdr, int fromPort, int inPort,QObject *parent): Gateway(parent){ this->fromAdr = QHostAddress(fromAdr); this->fromPort = fromPort; this->inPort = inPort; run();}void GatewayUdp::addRecipient(Gateway *recipient){ listRecipients.append(*recipient);}void GatewayUdp::readMessage(){ QByteArray data; while(udpSocket->hasPendingDatagrams()){ data.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(data.data(),data.size(),&fromAdr,&fromPort); } qDebug("GatewayUDP::readMessage() : date = ",data.data());}void GatewayUdp::sandMessage(QByteArray *data){ udpSocket->writeDatagram(*data,this->fromAdr,this->inPort);}void GatewayUdp::run(){ udpSocket = new QUdpSocket(); udpSocket->bind(this->fromAdr,this->fromPort); QObject::connect(udpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));}
#include <QApplication>int main(int c, char** v){ QApplication *app = new QApplication(c,v); return app->exec();}