ESP-IDF:TCP多线程并发服务器

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

实战派 ESP32-S3,双模无线开发板

ESP32-S3 原生支持 ESP-IDF,WiFi + 蓝牙一次搞定

核心代码:

核心思想就是主线程只处理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-S3,双模无线开发板

ESP32-S3 原生支持 ESP-IDF,WiFi + 蓝牙一次搞定

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值