You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
libUDPTCPNetwork/test-webserver.cc

105 lines
2.7 KiB

#include <unistd.h>
#include <sysexits.h>
#include <signal.h>
#include "UDPTCPNetwork.h"
#define DEFAULT_HTTP_PORT 2222
#define DEFAULT_HTTPS_PORT 2223
#define DEFAULT_CERT "./cert.pem"
#define DEFAULT_KEY "./privkey.pem"
#define MAX_CLIENTS 10
int running = 1;
static void sig_int(int);
int SetupSignals();
std::string GenerateHtmlFile();
class SimpleWebServer : public WebServer {
private:
protected:
public:
int HandleRequest (WebRequestBuffer *requestbuffer, WebServerClient *webclient);
};
int SimpleWebServer::HandleRequest (WebRequestBuffer *requestbuffer, WebServerClient *webclient) {
if (requestbuffer == NULL || webclient == NULL) return 0;
std::string request = requestbuffer->GetRequest();
printf ("SimpleWebServerClient::HandleRequest() Request:%s\n", request.c_str());
if (request.compare ("/") == 0) request = "/index.html";
if (request.find("/test.html") != std::string::npos) {
std::string htmlfile = GenerateHtmlFile();
if (webclient->SendResponseFileFromMemory(requestbuffer, request, "",
(void*) htmlfile.c_str(), strlen(htmlfile.c_str())) != 1) return 0;
}
else
if (webclient->SendResponseFile(requestbuffer, request, "") != 1) return 0;
requestbuffer->Clear();
return 1;
};
int main (int argc, char **argv) {
SimpleWebServer webserver;
SetupSignals();
webserver.SetupPorts(DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
webserver.SetupSSL(DEFAULT_KEY, DEFAULT_CERT);
webserver.Start();
running = 1;
while (running == 1) {
webserver.Loop();
usleep (1000);
}
};
int SetupSignals() {
if (signal(SIGINT, sig_int) == SIG_ERR) {
errorexit ("%s:%d could not set signal for SIGINT\n", __FILE__, __LINE__);
return 0;
}
if (signal(SIGTERM, sig_int) == SIG_ERR) {
errorexit ("%s:%d could not set signal for SIGTERM\n", __FILE__, __LINE__);
return 0;
}
if (signal(SIGHUP, sig_int) == SIG_ERR) {
errorexit ("%s:%d could not set signal for SIGHUB\n", __FILE__, __LINE__);
return 0;
}
if (signal(SIGUSR1, sig_int) == SIG_ERR) {
errorexit ("%s:%d could not set signal for SIGHUB\n", __FILE__, __LINE__);
return 0;
}
return 1;
};
static void sig_int(int sig) {
if (signal (SIGINT, sig_int) == SIG_ERR) errorexit ("could not set up signal SIGINT\n");
printf ("\n\nSignal Int\n\n");
running = 0;
}
std::string GenerateHtmlFile() {
std::string html;
html = "<html><head><title>Random Text</title></head><body>";
html += "<p>just some randdom number <b>";
html += to_string(rand());
html += "</b>.<p>Return to <a href=\"index.html\">INDEX.HTML</a></body></html>";
return html;
};