MG_EV_CLOSE received right after mg_send()

If you are asking a question, please follow this template:

  1. My goal is:
    [Would like to keep http connection open and continue sending POST request]
  2. My actions are:
  • Using the “Connection: keep-alive” in header during mg_connect_http() call, when MG_EV_HTTP_REPLY is received.
  • Call mg_print(buffer)

char buffer [] =
“POST / HTTP/1.1\r\n
Content-Type: text/html\r\n
Connection: keep-alive\r\n”
Content-Length: 10\r\n\r\n

  1. The result I see is:
  • mg_connect_http() for initial POST request
  • events received :

—> The connection does stay open in here

  • mg_print() for 2nd POST request

  • events received :

  • The connection close right after “MG_EV_HTTP_REPLY” is received

  • Have confirmed in connecting test server, it received both POST request contents.

  1. My expectation & question is:
    I want the connection stay opened and can use mg_print to continue sending multiple POST request.

Here is a very simple example using a public test server. It builds and runs ok on ubuntu, esp8266 and esp32.
Example output:

[Oct 29 18:29:53.678] main.c:57               3.054 - connected OK (mg_connection 0x3ffc766c)
[Oct 29 18:29:53.791] main.c:64               3.167 - Reply: {"id":4,"token":"QpwL5tke4Pnpja7X4"}
[Oct 29 18:30:06.624] main.c:103              16.000 - Request (reusing connection): host:, uri: /api/register, payload: {"email": ""}
[Oct 29 18:30:17.010] main.c:64               26.386 - Reply: {"error":"Missing password"}
[Oct 29 18:30:21.625] main.c:103              31.000 - Request (reusing connection): host:, uri: /api/login, payload: {"email": ""}
[Oct 29 18:30:21.735] main.c:64               31.111 - Reply: {"error":"Missing password"}
[Oct 29 18:30:36.624] main.c:103              46.000 - Request (reusing connection): host:, uri: /api/login, payload: {"email": "", "password": "123"}
[Oct 29 18:30:36.761] main.c:64               46.137 - Reply: {"token":"QpwL5tke4Pnpja7X4"}
[Oct 29 18:30:51.624] main.c:103              61.000 - Request (reusing connection): host:, uri: /api/register, payload: {"email": "", "password": "123"}
[Oct 29 18:30:52.163] main.c:64               61.538 - Reply: {"id":4,"token":"QpwL5tke4Pnpja7X4"}
[Oct 29 18:31:06.625] main.c:103              76.000 - Request (reusing connection): host:, uri: /api/register, payload: {"email": ""}
[Oct 29 18:31:06.750] main.c:64               76.126 - Reply: {"error":"Missing password"}

If you don’t close the connection when processing MG_EV_HTTP_REPLY, probably the server closes it.

My 2 cents: I see the POST specifies HTTP/1.1 and requests keep-alive, the server should honor that, check who is closing (and why) with a sniffer. If TLS gets in the middle do your testing in clear, though sometimes you can provide the keys to Wireshark (I don’t remember each case right now). I see you are using your internal network anyway.
Check your server’s timeout, Apache might close in 5s inactivity