Repository navigation
Expand file tree
/
Copy pathHttpServer.cpp
More file actions
73 lines (61 loc) · 2.04 KB
/
Copy pathHttpServer.cpp
File metadata and controls
73 lines (61 loc) · 2.04 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
66
67
68
69
70
71
72
73
#include "HttpServer.h"
#include <QtNetwork/QNetworkInterface>
#include <QtNetwork/QTcpSocket>
#include <iostream>
void HttpRequest::parse(const QString& in)
{
QStringList res = in.split(' ');
if (res.size() > 0) method = res[0];
if (res.size() > 1) target = res[1];
if (res.size() > 3) version = res[3];
}
HttpServer::HttpServer(QObject *parent, RequestCB* cb) :
QObject(parent),
reqCB(cb)
{
server = new QTcpServer(this);
// waiting for the web brower to make contact,this will emit signal
connect(server, SIGNAL(newConnection()),this, SLOT(myConnection()));
if(!server->listen(QHostAddress::Any,8090))
std::cout<< "\nWeb server could not start";
else
std::cout<<"\nWeb server is waiting for a connection on port 8090" << std::endl;
}
void HttpServer::myConnection()
{
socket = server->nextPendingConnection();
// Connect readyRead signal to process data asynchronously
connect(socket, &QTcpSocket::readyRead, this, &HttpServer::onReadyRead);
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}
void HttpServer::onReadyRead()
{
char webBrowerRXData[1000];
int sv = socket->read(webBrowerRXData, 1000);
bool ok = true;
if (reqCB)
{
HttpRequest req(webBrowerRXData);
ok = reqCB(req);
}
socket->write("HTTP/1.1 200 OK\r\n");
socket->write("Content-Type: text/html\r\n");
socket->write("Connection: close\r\n");
socket->write("\r\n");
socket->write("<!DOCTYPE html>\r\n");
if (ok)
socket->write("<html><body>OK<br><a href=\"/weather\">Weather</a><br><a href=\"/lcd\">Lcd</a></body>\n</html>\n");
else
socket->write("<html><body>NOK<br><a href=\"/weather\">Weather</a><br><a href=\"/lcd\">Lcd</a></body>\n</html>\n");
socket->flush();
// No need to deleteLater here - handled by disconnected signal
socket->disconnectFromHost();
}
HttpServer::~HttpServer()
{
if (socket) {
socket->close();
socket->deleteLater();
socket = nullptr;
}
}