Created
January 22, 2013 10:41
-
-
Save lamprosg/4593723 to your computer and use it in GitHub Desktop.
Qt - UDP sockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "myudp.h" | |
int main(int argc, char *argv[]) | |
{ | |
QCoreApplication a(argc, argv); | |
MyUDP server; | |
MyUDP server; | |
server.SayHello(); | |
return a.exec(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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