starting http server with error handling

This commit is contained in:
2025-03-14 18:24:42 +03:00
parent 453f907bfa
commit f507ec8d67
5 changed files with 88 additions and 30 deletions

View File

@@ -17,6 +17,8 @@ OFDScene::OFDScene(QWidget *parent)
: QWidget(parent)
, ui(new Ui::OFDScene) {
ui->setupUi(this);
QObject::connect(this, &OFDScene::httpErrorOccured, this, &OFDScene::notifyHttpServerFailure);
}
OFDScene::~OFDScene() {
@@ -25,6 +27,7 @@ OFDScene::~OFDScene() {
void OFDScene::startHttpServer() {
std::string localIp = "";
try {
localIp = get_local_ip_address();
} catch(std::exception e) {
@@ -32,13 +35,29 @@ void OFDScene::startHttpServer() {
return;
}
httplib::Server svr;
//TODO: generate random port from 1024 to 65535 and check if its used.
svr.Get("/", [&](const httplib::Request &, httplib::Response &res){
res.set_redirect("http://"+ localIp +":8080/", 301);
});
unsigned short number_of_retries = 0;
svr.listen("0.0.0.0", 8080);
do {
if (number_of_retries == 10) {
emit httpErrorOccured();
return;
}
this->port = rand() % (65535 - 1024) + 1024;
httplib::Server svr;
svr.Get("/", [&](const httplib::Request &, httplib::Response &res){
res.set_redirect("http://"+ localIp +":"+ std::to_string(port) +"/", 301);
});
number_of_retries ++;
std::cerr << "Listening on port: " << this->port << std::endl;
if (!svr.listen("0.0.0.0", this->port)) {
std::cerr << "Random port seems to be occupied. Trying to generate another one" << std::endl;
number_of_retries ++;
continue;
}
} while(true);
}
void OFDScene::on_choose_image_button_clicked() {
@@ -53,7 +72,6 @@ void OFDScene::on_choose_image_button_clicked() {
return;
}
ui->info_label->setText(tr("Selected image: ") + filename);
AdjustPictureDialog dialog = AdjustPictureDialog(this, filename.toStdString());
@@ -145,6 +163,19 @@ void OFDScene::on_parse_button_clicked() {
void OFDScene::on_binary_eye_button_clicked() {
http_thread = new std::thread(&OFDScene::startHttpServer, this);
}
void OFDScene::notifyHttpServerFailure() {
QMessageBox *infoDialog = new QMessageBox();
infoDialog->setText(tr("Could not start http server. 10 times in a row random port was occupied. Either you should run for a lottery ticket, or the problem is in the program. If the lottery ticket wasn't lucky, please, contact the developer."));
infoDialog->setIcon(QMessageBox::Warning);
infoDialog->setWindowTitle(tr("Could not start http server."));
infoDialog->exec();
delete infoDialog;
}
unsigned int OFDScene::getPort() {
return port;
}