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

116 lines
3.2 KiB

#include <unistd.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;
class SimpleWebSrvClient: public WebServerClient {
public:
SimpleWebSrvClient () {};
~SimpleWebSrvClient () {};
virtual int HandleRequest ();
};
int SimpleWebSrvClient::HandleRequest() {
std::string request = ReqBuffer.GetRequest();
int requesttype = ReqBuffer.GetType();
printf ("SimpleWebSrvClient::HandleRequest() Request:%s Type:%d\n", request.c_str(), requesttype);
if (request.compare ("/") == 0) request = "/index.html";
SendResponseFile(&ReqBuffer, request, "");
ReqBuffer.Clear();
return 1;
}
int main (int argc, char **argv) {
list<SimpleWebSrvClient*> webclients;
TCP http;
TCP https;
std::string ssl_cert = DEFAULT_CERT;
std::string ssl_key = DEFAULT_KEY;
if (http.Listen(DEFAULT_HTTP_PORT) != 1) {
printf ("error on listen\n");
exit (1);
}
printf ("test server is running on http://localhost:%d\n", DEFAULT_HTTP_PORT);
if (https.Listen(DEFAULT_HTTPS_PORT) != 1) {
printf ("error on listen\n");
exit (1);
}
printf ("test server is running on https://localhost:%d\n", DEFAULT_HTTPS_PORT);
while (running == 1) {
SimpleWebSrvClient *webclient = NULL;
list<SimpleWebSrvClient*>::iterator wci;
TCP *tcpclient = NULL;
int ssl_enabled = 1;
int res;
//
// any new connection?
if ((tcpclient = https.Accept()) == NULL) {
ssl_enabled = 0;
tcpclient = http.Accept();
}
if (tcpclient) {
printf ("new %s connection from %s\n", ssl_enabled ? "HTTPS" : "HTTP", tcpclient->GetRemoteAddr().c_str());
if (webclients.size() > MAX_CLIENTS) {
printf ("max connections reached. closing connection.\n");
tcpclient->Close();
delete tcpclient;
continue;
}
webclient = new SimpleWebSrvClient();
if (ssl_enabled) res = webclient->Accept(tcpclient, ssl_key, ssl_cert);
else res = webclient->Accept(tcpclient);
if (res == 0) {
printf ("webclient could not connect. closing connection\n");
delete webclient;
delete tcpclient;
continue;
}
webclient->SetDecoumentRoot("./www");
webclients.push_back(webclient);
printf ("add new connection to client list\n");
}
//
// go through all the clients and check for new requests
for (wci = webclients.begin(); wci != webclients.end(); wci++) {
int res = 0;
webclient = *wci;
res = webclient->Loop();
if (res == -1) {
// error on loop, remove and delete webclient.
printf ("remove connection\n");
webclients.remove(webclient);
delete webclient;
wci = webclients.begin();
if (wci == webclients.end()) continue;
}
}
usleep (1000);
}
};