-
Notifications
You must be signed in to change notification settings - Fork 4
/
ServerDiscovery.cpp
72 lines (62 loc) · 2.22 KB
/
ServerDiscovery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "ServerDiscovery.hpp"
#include <QDebug>
#include <QUdpSocket>
#include <QNetworkInterface>
static const quint16 s_udpPort = 29031;
static const QByteArray s_header = "IsitMessenger";
ServerDiscovery::ServerDiscovery(QObject *parent) :
QObject(parent)
{
m_haveServer = false;
m_udpSocket = new QUdpSocket(this);
m_udpSocket->bind(QHostAddress::Any, s_udpPort, QAbstractSocket::ShareAddress|QAbstractSocket::ReuseAddressHint);
connect(m_udpSocket, SIGNAL(readyRead()),
this, SLOT(onUdpMessageReceived()));
}
void ServerDiscovery::addServer(quint16 port)
{
m_haveServer = true;
m_port = port;
announceServer();
}
void ServerDiscovery::onUdpMessageReceived()
{
qDebug() << Q_FUNC_INFO;
while (m_udpSocket->hasPendingDatagrams()) {
QByteArray buffer;
buffer.resize(m_udpSocket->pendingDatagramSize());
QHostAddress address;
m_udpSocket->readDatagram(buffer.data(), buffer.size(), &address);
if (buffer == s_header+":?"){
qDebug() << Q_FUNC_INFO << "Server requested by client" << address.toString();
announceServer();
} else {
QList<QByteArray> lBuff = buffer.split(':');
quint16 port = lBuff[1].toUInt();
qDebug() << Q_FUNC_INFO << "Server found at" << address.toString() << ":" << port;
emit serverFound(address.toString(),port);
}
}
}
void ServerDiscovery::announceServer()
{
if (m_haveServer){
for (QNetworkInterface iface : QNetworkInterface::allInterfaces()){
for (QNetworkAddressEntry entry : iface.addressEntries()) {
QString datagram = s_header + ":" + QString::number(m_port);
m_udpSocket->writeDatagram(datagram.toLatin1(), entry.broadcast(), s_udpPort);
}
}
qDebug() << Q_FUNC_INFO << "Announcing server";
}
}
void ServerDiscovery::discoveryServer()
{
qDebug() << Q_FUNC_INFO;
for (QNetworkInterface iface : QNetworkInterface::allInterfaces()){
for (QNetworkAddressEntry entry : iface.addressEntries()) {
QString datagram = s_header + ":?";
m_udpSocket->writeDatagram(datagram.toLatin1(), entry.broadcast(), s_udpPort);
}
}
}