| 1 | // Copyright (C) 2016 The Qt Company Ltd. |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only |
| 3 | |
| 4 | #include "networkcontroller.h" |
| 5 | |
| 6 | NetworkController::NetworkController(QObject *parent) : |
| 7 | QObject(parent) |
| 8 | { |
| 9 | QObject::connect(&m_server, &QTcpServer::newConnection, this, &NetworkController::newConnection); |
| 10 | |
| 11 | if (!m_server.listen(QHostAddress::Any, 8080)) { |
| 12 | qDebug() << "Failed to run http server"; |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | void NetworkController::newConnection() |
| 17 | { |
| 18 | QTcpSocket *socket = m_server.nextPendingConnection(); |
| 19 | |
| 20 | if (!socket) |
| 21 | return; |
| 22 | |
| 23 | QObject::connect(socket, &QAbstractSocket::disconnected, this, &NetworkController::disconnected); |
| 24 | QObject::connect(socket, &QIODevice::readyRead, this, &NetworkController::readyRead); |
| 25 | } |
| 26 | |
| 27 | void NetworkController::disconnected() |
| 28 | { |
| 29 | QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender()); |
| 30 | if (!socket) |
| 31 | return; |
| 32 | |
| 33 | socket->disconnect(); |
| 34 | socket->deleteLater(); |
| 35 | } |
| 36 | |
| 37 | void NetworkController::readyRead() |
| 38 | { |
| 39 | QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender()); |
| 40 | if (!socket || socket->state() == QTcpSocket::ClosingState) |
| 41 | return; |
| 42 | |
| 43 | QString requestData = socket->readAll(); |
| 44 | QStringList list = requestData.split(' '); |
| 45 | QString path = list[1]; |
| 46 | list = path.split('/'); |
| 47 | |
| 48 | QByteArray reply; |
| 49 | if (list.count() == 3) { |
| 50 | socket->write("HTTP/1.1 200 OK\r\n"); |
| 51 | reply = QStringLiteral("Command accepted: %1 %2").arg(list[1], list[2]).toUtf8(); |
| 52 | emit commandAccepted(list[1], list[2]); |
| 53 | } else { |
| 54 | socket->write("HTTP/1.1 404 Not Found\r\n"); |
| 55 | reply = "Command rejected"; |
| 56 | } |
| 57 | |
| 58 | socket->write("Content-Type: text/plain\r\n"); |
| 59 | socket->write(QStringLiteral("Content-Length: %1\r\n").arg(reply.size()).toUtf8()); |
| 60 | socket->write("Connection: close\r\n"); |
| 61 | socket->write("\r\n"); |
| 62 | socket->write(reply); |
| 63 | socket->disconnectFromHost(); |
| 64 | } |