Friday, December 7, 2012

How to write a UDP socket program in Qt


We have seen how to write a simple UDP socket program in C (Linux) in the earlier post..

Now we are going to learn how to write a simple UDP socket program in Qt..

In the following example we used to send and receive data on localhost address.
And the readyRead() signal and slot is used whenever the data receives on the given socket (i.e. socket reday for read data), the control goes to slot method.
writeDatagram() and readDatagram() API's used for sending and receiving data on the given udp socket.

Before starting the Program to write, create a Project using following steps 
  • open Qt creator
  • Create Project
  • Select Other Project in Projects tab then select Qt Console Application, then click on choose...
  • Then give the Project name
  • And then click on Next, Finish in the following dialog boxes
  • Then open the .pro file and write QT += network 
  • To create the cpp file Right click on the project then choose Add new


myudp.h:

#ifndef MYUDP_H
#define MYUDP_H

#include <QObject>
#include <QUdpSocket>

class MyUDP : public QObject
{
    Q_OBJECT
public:
    explicit MyUDP(QObject *parent = 0);
    void WriteData();
signals:
    
public slots:
    void readReady();
private:
    QUdpSocket *socket;
    
};

#endif // MYUDP_H


myudp.c

#include "myudp.h"
MyUDP::MyUDP(QObject *parent) :QObject(parent)
{
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::LocalHost,5678);
    connect(socket,SIGNAL(readyRead()),this,SLOT(readReady()));
}
void MyUDP::WriteData()
{
    QByteArray msg;
    msg.append("Hello!!!");
    socket->writeDatagram(msg,QHostAddress::LocalHost,5678);
}
void MyUDP::readReady()
{
    QByteArray buffer;
    buffer.resize(socket->pendingDatagramSize());
    QHostAddress sender;
    quint16 port;
    socket->readDatagram(buffer.data(),buffer.size(),&sender,&port);
    qDebug()<<"Message From: " << sender.toString();
    qDebug()<<"With Port Number " << port;
    qDebug()<<"Message: " << buffer;
}

main.c

#include <QtCore/QCoreApplication>
#include "myudp.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    MyUDP client;

    client.WriteData();

    return a.exec();
}
-->
Output:


5 comments:

  1. Hello, your coude was usefull for me. But When I split server and client in separate machines connect(socket,SIGNAL(readyRead()),this,SLOT(readReady())); is never fire. Could you help me with that?
    thank you

    ReplyDelete
  2. Exactly what i wanted, thank you

    ReplyDelete
  3. how to send a double in udp?

    ReplyDelete
    Replies
    1. Append double value as below to byte array data...

      QByteArray msg;
      double dVal=8.56;
      msg.append(QByteArray::number(dVal));

      Delete
  4. good one. But if i were to split the two, how do I keep receiver program constantly alive to listen to incoming datagrams?

    ReplyDelete