-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerClass.cpp
More file actions
65 lines (59 loc) · 2.3 KB
/
ServerClass.cpp
File metadata and controls
65 lines (59 loc) · 2.3 KB
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
#include "ServerClass.h"
#include "ui_serverclass.h"
#include <QDebug>
#include <QNetworkInterface>
#include <QHostAddress>
// Utility to get local WiFi IP address
QString getWifiIPv4Address() {
QString wifiIPv4;
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for (const QNetworkInterface& iface : interfaces) {
if (iface.flags().testFlag(QNetworkInterface::IsUp) &&
iface.flags().testFlag(QNetworkInterface::IsRunning) &&
!iface.flags().testFlag(QNetworkInterface::IsLoopBack)) {
qDebug() << iface.humanReadableName();
for (const QNetworkAddressEntry& entry : iface.addressEntries()) {
if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
wifiIPv4 = entry.ip().toString();
if (iface.humanReadableName().contains("wlan", Qt::CaseInsensitive) ||
iface.humanReadableName().contains("wi-fi", Qt::CaseInsensitive) ||
iface.humanReadableName().contains("wireless", Qt::CaseInsensitive) ||
iface.humanReadableName().contains("wlx", Qt::CaseInsensitive)) {
return wifiIPv4;
}
}
}
}
}
return wifiIPv4;
}
ServerClass::ServerClass(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::ServerClass)
, server(new QTcpServer(this))
{
ui->setupUi(this);
setWindowTitle("Server");
QString ip = getWifiIPv4Address();
ui->label_3->setText(ip.isEmpty() ? "IP not found" : ip);
if (server->listen(QHostAddress::Any, 9001)) {
connect(server, &QTcpServer::newConnection, this, &ServerClass::handleNewConnection);
ui->label_4->setText("Waiting for connections...");
} else {
ui->label_4->setText("Server failed to start");
qDebug() << "Error starting server:" << server->errorString();
}
}
void ServerClass::handleNewConnection()
{
while (server->hasPendingConnections()) {
QTcpSocket* newSocket = server->nextPendingConnection();
channels* clientChannel = new channels(newSocket, this);
clients.append(clientChannel);
ui->label_4->setText(QString("Clients connected: %1").arg(clients.size()));
}
}
ServerClass::~ServerClass()
{
delete ui;
}