Webserver for peach-board
Diff: HTTPServer.cpp
- Revision:
- 0:6ec14f880a00
- Child:
- 1:f1f734dd23ee
diff -r 000000000000 -r 6ec14f880a00 HTTPServer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HTTPServer.cpp Wed Mar 04 02:16:31 2015 +0000 @@ -0,0 +1,131 @@ +#include "HTTPServer.h" + +#define INVALID_FORMATTER "No valid formatter specified" + +bool cmp(char* a, char* b) +{ + return strcmp(a,b) < 0; +} + +HTTPServer::HTTPServer(Formatter *f): +socket(), +handlers(&cmp), +formatter(f), +reply(), +command() +{ +} + +HTTPServer::~HTTPServer() +{ + for(std::map<char*, RequestHandler*>::iterator itor = handlers.begin(); + itor != handlers.end(); + ++itor) + delete itor->second; + + if(formatter) + delete formatter; +} + +bool HTTPServer::init(int port) +{ + socket.set_blocking(true); + if(socket.bind(port)) + { + printf("Could not bind on port %d.\n", port); + return false; + } + + if(socket.listen()) + { + printf("Could not listen %d\n", port); + return false; + } + + return true; +} + +void HTTPServer::run() +{ + TCPSocketConnection c; + while(true) + { + while(socket.accept(c)); + c.set_blocking(false, 1000); + while(c.is_connected()) + { + char buffer[512]; + int n = c.receive_all(buffer, sizeof(buffer)-1); + if(n == 0) + { + printf("Close "); + c.close(); + break; + } + else if(n != -1) + { + printf("Received data\n"); + buffer[n] = '\0'; + handle_request(buffer); + if(formatter != NULL) + { + printf("Sending data..."); + char *page = formatter->get_page(reply); + do + { + c.send(page, strlen(page)+1); + page = formatter->get_page(reply); + }while(strlen(page)>0); + printf("done\n"); + } + else{ + printf("Format NULL"); + c.send(INVALID_FORMATTER, strlen(INVALID_FORMATTER)+1); + } + } + else + printf("Error while receiving data\n"); + } + } +} + +void HTTPServer::handle_request(char *buffer) +{ + char *request_type = strtok(buffer, " "); + char *request = strtok(NULL, " "); + + printf("%s\n",request_type); + + reply[0] = '\0'; + if(!strcmp(request, "/")){ + printf("in /\n"); + return; + } + + if(!command.decode(request)) + { + strcat(reply, "Malformed request"); + printf("%s\n",reply); + return; + } + + std::map<char*, RequestHandler*>::iterator itor = handlers.find(request_type); + if(itor == handlers.end()) + { + strcat(reply, "No request handler found for this type of request."); + printf("%s\n",reply); + return; + } + if(itor->second != NULL) + itor->second->handle(command, reply); + else{ + strcat(reply, "Invalid request handler"); + printf("%s\n",reply); + } +} + +void HTTPServer::add_request_handler(char *name, RequestHandler* handler) +{ + handlers[name] = handler; +} +