Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created January 22, 2013 10:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamprosg/4593723 to your computer and use it in GitHub Desktop.
Save lamprosg/4593723 to your computer and use it in GitHub Desktop.
Qt - UDP sockets
#include "myudp.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyUDP server;
MyUDP server;
server.SayHello();
return a.exec();
}
#include "myudp.h"
MyUDP::MyUDP(QObject *parent) :
QObject(parent)
{
socket = new QUdpSocket(this);
//We need to bind the UDP socket to an address and a port
socket->bind(QHostAddress::LocalHost,1234); //ex. Address localhost, port 1234
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
}
void MyUDP::SayHello() //Just spit out some data
{
QByteArray Data;
Data.append("Hello from UDP land");
socket->writeDatagram(Data,QHostAddress::LocalHost,1234);
//If you want to broadcast something you send it to your broadcast address
//ex. 192.2.1.255
}
void MyUDP::readyRead() //Read something
{
QByteArray Buffer;
Buffer.resize(socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort);
//The address will be sender.toString()
}
//Base class QObject
#include <QUdpSocket>
class MyUDP : public QObject
{
Q_OBJECT
public:
explicit MyUDP(QObject *parent = 0);
void SayHello();
private:
QUdpSocket *socket;
signals:
public slots:
void readyRead();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment