|
| 1 | +/* |
| 2 | + * This example demonstrates how to send an HTTP response using chunks |
| 3 | + * It will create an HTTP Server (port 80) associated with an a MDNS service |
| 4 | + * Access the HTTP server using a Web Browser: |
| 5 | + * URL can be composed using the MDNS name "esp32_chunk_resp.local" |
| 6 | + * http://esp32_chunk_resp.local/ |
| 7 | + * or the IP Address that will be printed out, such as for instance 192.168.1.10 |
| 8 | + * http://192.168.1.10/ |
| 9 | + * |
| 10 | + * ESP32 Server response can also be viewed using the curl command: |
| 11 | + * curl -i esp32_chunk_resp.local:80 |
| 12 | + * curl -i --raw esp32_chunk_resp.local:80 |
| 13 | + */ |
| 14 | + |
| 15 | + |
| 16 | +#include <WiFi.h> |
| 17 | +#include <NetworkClient.h> |
| 18 | +#include <WebServer.h> |
| 19 | +#include <ESPmDNS.h> |
| 20 | + |
| 21 | +const char *ssid = "........"; |
| 22 | +const char *password = "........"; |
| 23 | + |
| 24 | +WebServer server(80); |
| 25 | + |
| 26 | +void handleChunks() { |
| 27 | + uint8_t countDown = 10; |
| 28 | + //server.chunkResponseBegin("Transfer-Encoding: chunked"); |
| 29 | + server.chunkResponseBegin(); |
| 30 | + char countContent[8]; |
| 31 | + while (countDown) { |
| 32 | + sprintf(countContent, "%d...\r\n", countDown--); |
| 33 | + server.chunkWrite(countContent, strlen(countContent)); |
| 34 | + // count down shall show up in the browser only after about 5 seconds when finishing the whole transmission |
| 35 | + // using "curl -i esp32_chunk_resp.local:80", it will show the count down as it sends each chunk |
| 36 | + delay(500); |
| 37 | + } |
| 38 | + server.chunkWrite("DONE!", 5); |
| 39 | + server.chunkResponseEnd(); |
| 40 | +} |
| 41 | + |
| 42 | +void setup(void) { |
| 43 | + Serial.begin(115200); |
| 44 | + WiFi.mode(WIFI_STA); |
| 45 | + WiFi.begin(ssid, password); |
| 46 | + Serial.println(""); |
| 47 | + |
| 48 | + // Wait for connection |
| 49 | + while (WiFi.status() != WL_CONNECTED) { |
| 50 | + delay(500); |
| 51 | + Serial.print("."); |
| 52 | + } |
| 53 | + Serial.println(""); |
| 54 | + Serial.print("Connected to "); |
| 55 | + Serial.println(ssid); |
| 56 | + Serial.print("IP address: "); |
| 57 | + Serial.println(WiFi.localIP()); |
| 58 | + |
| 59 | + // Use the URL: http://esp32_chunk_resp.local/ |
| 60 | + if (MDNS.begin("esp32_chunk_resp")) { |
| 61 | + Serial.println("MDNS responder started"); |
| 62 | + } |
| 63 | + |
| 64 | + server.on("/", handleChunks); |
| 65 | + |
| 66 | + server.onNotFound([]() { |
| 67 | + server.send(404, "text/plain", "Page not found"); |
| 68 | + }); |
| 69 | + |
| 70 | + server.begin(); |
| 71 | + Serial.println("HTTP server started"); |
| 72 | +} |
| 73 | + |
| 74 | +void loop(void) { |
| 75 | + server.handleClient(); |
| 76 | + delay(2); //allow the cpu to switch to other tasks |
| 77 | +} |
0 commit comments