Webserver example for mbed OS 5 - HTTP 1.1 and multi-threaded
Dependencies: mbed-http
main.cpp
00001 #include "mbed.h" 00002 #include "easy-connect.h" 00003 #include "http_server.h" 00004 #include "http_response_builder.h" 00005 00006 Serial pc(USBTX, USBRX); 00007 DigitalOut led(LED1); 00008 00009 // Requests come in here 00010 void request_handler(ParsedHttpRequest* request, TCPSocket* socket) { 00011 00012 printf("Request came in: %s %s\n", http_method_str(request->get_method()), request->get_url().c_str()); 00013 00014 if (request->get_method() == HTTP_GET && request->get_url() == "/") { 00015 HttpResponseBuilder builder(200); 00016 builder.set_header("Content-Type", "text/html; charset=utf-8"); 00017 00018 char response[] = "<html><head><title>Hello from mbed</title></head>" 00019 "<body>" 00020 "<h1>mbed webserver</h1>" 00021 "<button id=\"toggle\">Toggle LED</button>" 00022 "<script>document.querySelector('#toggle').onclick = function() {" 00023 "var x = new XMLHttpRequest(); x.open('POST', '/toggle'); x.send();" 00024 "}</script>" 00025 "</body></html>"; 00026 00027 builder.send(socket, response, sizeof(response) - 1); 00028 } 00029 else if (request->get_method() == HTTP_POST && request->get_url() == "/toggle") { 00030 printf("toggle LED called\n"); 00031 led = !led; 00032 00033 HttpResponseBuilder builder(200); 00034 builder.send(socket, NULL, 0); 00035 } 00036 else { 00037 HttpResponseBuilder builder(404); 00038 builder.send(socket, NULL, 0); 00039 } 00040 } 00041 00042 int main() { 00043 pc.baud(115200); 00044 00045 // Connect to the network (see mbed_app.json for the connectivity method used) 00046 NetworkInterface* network = easy_connect(true); 00047 if (!network) { 00048 printf("Cannot connect to the network, see serial output\n"); 00049 return 1; 00050 } 00051 00052 HttpServer server(network); 00053 nsapi_error_t res = server.start(8080, &request_handler); 00054 00055 if (res == NSAPI_ERROR_OK) { 00056 printf("Server is listening at http://%s:8080\n", network->get_ip_address()); 00057 } 00058 else { 00059 printf("Server could not be started... %d\n", res); 00060 } 00061 00062 wait(osWaitForever); 00063 }
Generated on Tue Jul 12 2022 20:47:19 by 1.7.2