3 Nisan 2017 Pazartesi

QUDP SOCKET

myudp.h


#ifndef MYUDP_H
#define MYUDP_H
#include < QObject>
#include< QUdpSocket>
class MyUDP : public QObject
{
    Q_OBJECT
public:
    explicit MyUDP(QObject *paretnt = 0);
    void SayHello();
signals:
public slots:
    void readyRead();
private:
    QUdpSocket *socket;
};

#endif // MYUDP_H



-------------------------------------------------------
 main.cpp


#include 
#include "myudp.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    MyUDP server;
    MyUDP client;
    client.SayHello();
    client.SayHello();
    return a.exec();
}


---------------------------------------------------------
myudp.cpp


#include " myudp.h"
MyUDP::MyUDP(QObject *parent):
    QObject(parent)
{


    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::Any,1234);
    connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));

}
void MyUDP::SayHello()
{
    QByteArray Data;
    Data.append("Hello from UDP ");
    socket->writeDatagram(Data,QHostAddress::LocalHost,1234);
}
void MyUDP::readyRead()
{
    QByteArray Buffer;
    Buffer.resize(socket->pendingDatagramSize());
    QHostAddress sender;
    quint16 senderPort;
    socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort);
    qDebug() < < "Message From : " << sender.toString();
    qDebug() < < "Message Port : " << senderPort;
    qDebug() < < "Message : " << Buffer << "\n\n\n";

}



Share: