核心代码:
核心思想就是主线程只处理socket监听功能,把数据处理部分分配到不同的线程中去处理。来了一个客户端连接,就分配新的线程去处理该客户端的数据请求。

代码:
/多线程并发服务器/
#include <stdio.h>
#include “sdkconfig.h”
#include “freertos/semphr.h”
#include “esp_system.h”
#include “esp_spi_flash.h”
#include <string.h>
#include “freertos/FreeRTOS.h”
#include “freertos/task.h”
#include “freertos/event_groups.h”
#include “esp_system.h”
#include “esp_wifi.h”
#include “esp_event.h”
#include “esp_event_loop.h”
#include “esp_log.h”
#include “nvs_flash.h”
#include “sdkconfig.h”
#include “lwip/err.h”
#include “lwip/sys.h”
#include “mdns.h”
#include <sys/param.h>
#include “esp_event.h”
#include “esp_netif.h”
//#include “protocol_examples_common.h”
#include “lwip/sockets.h”
#include <lwip/netdb.h>
/* The examples use WiFi configuration that you can set via ‘make menuconfig’.
If you’d rather not, just change the below entries to strings with
the config you want - ie #define EXAMPLE_WIFI_SSID “mywifissid”
*/
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY
#define EXAMPLE_ESP_WIFI_AP_SSID CONFIG_ESP_WIFI_AP_SSID
#define EXAMPLE_ESP_WIFI_AP_PASS CONFIG_ESP_WIFI_AP_PASSWORD
#define EXAMPLE_MAX_STA_CONN CONFIG_MAX_STA_CONN
#define EXAMPLE_IP_ADDR CONFIG_SERVER_IP
#define EXAMPLE_ESP_WIFI_AP_CHANNEL CONFIG_ESP_WIFI_AP_CHANNEL
static const char *TAG = “camera wifi”;
static const char *TAG1 = “michael add:”;
static int s_retry_num = 0;
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_AP_STACONNECTED:
ESP_LOGI(TAG, “station:” MACSTR " join, AID=%d",
MAC2STR(event->event_info.sta_connected.mac),
event->event_info.sta_connected.aid);
break;
case SYSTEM_EVENT_AP_STADISCONNECTED:
ESP_LOGI(TAG, “station:” MACSTR “leave, AID=%d”,
MAC2STR(event->event_info.sta_disconnected.mac),
event->event_info.sta_disconnected.aid);
break;
case SYSTEM_EVENT_STA_START:
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_GOT_IP:
ESP_LOGI(TAG, “got ip:%s”,
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
s_retry_num = 0;
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
{
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(TAG,“retry to connect to the AP”);
}
ESP_LOGI(TAG,“connect to the AP fail”);
break;
}
default:
break;
}
ESP_LOGI(TAG1,“before mdns_handle_system_event”);
mdns_handle_system_event(ctx, event);

代码示例展示了一个ESP32设备如何初始化Wi-Fi(AP和STA模式),并实现一个多线程TCP服务器。当有客户端连接时,服务器创建新线程来处理客户端的数据请求。接收到数据后,服务器会回传数据并附上处理线程的标识(例如task0reply或task1reply)。

3083

被折叠的 条评论
为什么被折叠?



