Layer: L4 Transport ยท Build flags: PC_ENABLE_KEEPALIVE
What this example teaches
By default the server answers one request per TCP connection and closes it (Connection: close). With keep-alive enabled, one connection serves many requests - the big win when a browser loads a page plus its assets, or a client polls an endpoint. The crucial point: it is transparent to your handlers. You write the same routes; the server decides keep-alive vs close and emits the right Connection header.
The behavior rules. Keep-alive follows the HTTP spec, with safety bounds:
- HTTP/1.1: the connection stays open unless the client sends
Connection: close.
- HTTP/1.0: it closes unless the client sends
Connection: keep-alive.
- Error responses (400/413/414) always close - the next request boundary is unknown after a parse error.
- Each connection serves at most
PC_KEEPALIVE_MAX_REQUESTS, then closes.
- Idle connections are still reclaimed by the
conn_timeout sweep.
There is no API to learn. Enabling the flag changes the transport behavior; the handlers below are ordinary. The /time route exists just so a client can poll repeatedly over the same socket and watch it being reused:
char buf[32];
snprintf(buf, sizeof(buf), "uptime_ms=%lu", (unsigned long)millis());
server.send(id, 200, "text/plain", buf);
});
@ HTTP_GET
Safe, idempotent read.
Fully-parsed HTTP/1.1 request.
Build-flag note. PC_ENABLE_KEEPALIVE must reach the library build, so pass it as a build_flag (an in-sketch #define only affects the sketch). You can also tune PC_KEEPALIVE_MAX_REQUESTS the same way.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--project-option="build_flags=-DPC_ENABLE_KEEPALIVE=1" \
--lib="." examples/L4-Transport/KeepAlive/KeepAlive.ino
curl -v http://<ip>/ # note "Connection: keep-alive"
curl -v http://<ip>/ http://<ip>/time http://<ip>/ # one socket serves all three
Annotated source
The complete sketch (KeepAlive.ino), reproduced verbatim with added explanatory comments:
#define PC_ENABLE_KEEPALIVE 1
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
static const char PAGE[] = "<!doctype html><html><body><h1>Keep-Alive demo</h1>"
"<p>This page and its requests are served over one persistent connection.</p>"
"<p><a href=\"/time\">/time</a></p></body></html>";
void setup()
{
Serial.print("Connecting to WiFi");
{
delay(250);
Serial.print('.');
}
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
char buf[32];
snprintf(buf, sizeof(buf), "uptime_ms=%lu", (unsigned long)millis());
server.
send(
id, 200,
"text/plain", buf);
});
int32_t result = server.
begin(80);
if (result < 0)
Serial.printf("begin() failed (error %d)\n", result);
else
Serial.println("HTTP server (keep-alive) on :80");
}
void loop()
{
}
Single-port HTTP server with deterministic, zero-allocation execution.
void send(uint8_t slot_id, int code, const char *content_type, const char *payload)
Send an HTTP response with a body and close the connection.
int32_t begin(const WebServerConfig *cfg=nullptr)
Initialize all connection slots and open all registered listeners.
void on(const char *path, HttpMethod method, Handler callback)
Register a route handler.
void handle()
Drive the server - call every Arduino loop() iteration.
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.