When I create one, it works. When I add the second it fails. Am I doing it wrong, or is the http_server not capable of doing more than one.
Code: Select all
static const char *TAG = "DualWebServer";
// Handler for requests to the server on port 80
esp_err_t port80_handler(httpd_req_t *req)
{
httpd_resp_send(req, "Hello from server on port 80!", HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
// Handler for requests to the server on port 8080
esp_err_t port8080_handler(httpd_req_t *req)
{
httpd_resp_send(req, "Hello from server on port 8080!", HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
// Function to start a server on a specified port
httpd_handle_t start_http_server1(int port, esp_err_t (*handler)(httpd_req_t *))
{
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = port;
httpd_handle_t server = NULL;
if (httpd_start(&server, &config) == ESP_OK)
{
httpd_uri_t uri = {
.uri = "/",
.method = HTTP_GET,
.handler = handler,
.user_ctx = NULL};
httpd_register_uri_handler(server, &uri);
ESP_LOGI(TAG, "Server started on port %d", port);
return server;
}
ESP_LOGE(TAG, "Failed to start server on port %d", port);
return NULL;
}
// Function to start a server on a specified port
httpd_handle_t start_http_server2(int port, esp_err_t (*handler)(httpd_req_t *))
{
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = port;
httpd_handle_t server = NULL;
if (httpd_start(&server, &config) == ESP_OK)
{
httpd_uri_t uri = {
.uri = "/",
.method = HTTP_GET,
.handler = handler,
.user_ctx = NULL};
httpd_register_uri_handler(server, &uri);
ESP_LOGI(TAG, "Server started on port %d", port);
return server;
}
ESP_LOGE(TAG, "Failed to start server on port %d", port);
return NULL;
}
void main(void)
{
// start wifi stuff left out for clarity
// Start the first HTTP server on port 80
httpd_handle_t server1 = start_http_server1(80, port80_handler);
// Start the second HTTP server on port 8080
httpd_handle_t server2 = start_http_server2(8080, port8080_handler);
}