123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- #include "broadcast.h"
-
- Broadcast::Broadcast(bool isServer, QObject* p) : QObject(p)
- {
- m_isServer = isServer;
- m_server = new QUdpSocket(this);
- connect(m_server, SIGNAL(readyRead()), this, SLOT(readyRead()));
- connect(&m_timeoutTimer, SIGNAL(timeout()), this, SLOT(clearData()));
- connect(&m_bcTimer, SIGNAL(timeout()), this, SLOT(broadcastClient()));
- m_timeoutTimer.setSingleShot(true);
- m_bcTimer.setSingleShot(true);
- setTimeout(2500);
- setBroadcastInterval(5000);
- }
-
- QString Broadcast::getError() const
- {
- return m_server->errorString();
- }
-
- bool Broadcast::isServer() const
- {
- return m_isServer;
- }
-
- QByteArray Broadcast::clientData()
- {
- return PTSocket::handshakeData() + "bcastc";
- }
-
- QByteArray Broadcast::serverData()
- {
- return PTSocket::handshakeData() + "bcasts";
- }
-
- void Broadcast::setTimeout(int t)
- {
- if(m_timeoutTimer.isActive())
- m_timeoutTimer.start(t);
- else
- m_timeoutTimer.setInterval(t);
- }
-
- void Broadcast::setBroadcastInterval(int t)
- {
- if(m_bcTimer.isActive())
- m_bcTimer.start(t);
- else
- m_bcTimer.setInterval(t);
- }
-
- bool Broadcast::start(int port, int r, QHostAddress ad)
- {
- m_remotePort = r;
- bool ok = m_server->bind(ad, port);
- if(m_isServer)
- m_server->writeDatagram(serverData(), QHostAddress::Broadcast, m_remotePort);
- else
- broadcastClient();
- return ok;
- }
-
- void Broadcast::broadcastClient()
- {
- m_server->writeDatagram(clientData(), QHostAddress::Broadcast, m_remotePort);
- // m_bcTimer.start();
- }
-
- void Broadcast::readyRead()
- {
- while(m_server->hasPendingDatagrams())
- {
- QByteArray data;
- data.resize(m_server->pendingDatagramSize());
- QHostAddress host;
- quint16 port = 0;
- m_server->readDatagram(data.data(), data.size(), &host, &port);
- BcClient client(host.toIPv4Address(), port);
- m_data[client].append(data);
- if(m_isServer)
- {
- if(m_data[client].size() < clientData().size())
- continue;
- if(m_data[client] == clientData())
- m_server->writeDatagram(serverData(), QHostAddress(client.first), m_remotePort);
- m_data.remove(client);
- }
- else
- {
- if(m_data[client].size() < serverData().size())
- continue;
- if(m_data[client] == serverData())
- emit serverDiscovered(QHostAddress(client.first), client.second);
- m_data.remove(client);
- }
- }
- m_timeoutTimer.start();
- }
-
- void Broadcast::clearData()
- {
- m_data.clear();
- }
|