基于ESP32的TCP/IP传输实现

打印 上一主题 下一主题

主题 924|帖子 924|积分 2772

TCP/IP协议原理

TCP/IP协议是Internet互联网最基本的协议,TCP/IP协议的应用层的主要协议有HTTP、Telnet、FTP、SMTP等,是用来读取来自传输层的数据或者将数据传输写入传输层;传输层的主要协议有UDP、TCP,实现端对端的数据传输;网络层的主要协议有ICMP、IP、IGMP,主要负责网络中数据包的传送等;链路层有时也称作数据链路层或网络接口层,主要协议有ARP、RARP,通常包括操作系统中的设备驱动程序和计算机中对应的网络接口卡,它们一起处理与传输媒介(如电缆或其他物理设备)的物理接口细节。
TCP协议是一个面向连接的、可靠的传输协议,它提供一种可靠的字节流,能保证数据完整、无损并且按顺序到达。TCP尽量连续不断地测试网络的负载并且控制发送数据的速度以避免网络过载。另外,TCP试图将数据按照规定的顺序发送。
ESP32作为热点+TCP服务端

参考乐鑫开源程序,设置wifi模式为AP,运行TCP服务端程序。
ESP32作为站点+TCP客户端

参考乐鑫开源程序,设置wifi模式为STA,运行TCP客户端程序。
AP+TCP服务端程序

主函数
  1. #include <string.h>
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "esp_mac.h"
  5. #include "esp_wifi.h"
  6. #include "esp_event.h"
  7. #include "esp_log.h"
  8. #include "nvs_flash.h"
  9. #include "lwip/err.h"
  10. #include "lwip/sys.h"
  11. #include "tcp_server.h"
  12. /* The examples use WiFi configuration that you can set via project configuration menu.
  13.    If you'd rather not, just change the below entries to strings with
  14.    the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
  15. */
  16. //#define EXAMPLE_ESP_WIFI_SSID      CONFIG_ESP_WIFI_SSID
  17. //#define EXAMPLE_ESP_WIFI_PASS      CONFIG_ESP_WIFI_PASSWORD
  18. #define EXAMPLE_ESP_WIFI_SSID      "myesp32AP"
  19. #define EXAMPLE_ESP_WIFI_PASS      "esp45678"
  20. #define EXAMPLE_ESP_WIFI_CHANNEL   CONFIG_ESP_WIFI_CHANNEL
  21. #define EXAMPLE_MAX_STA_CONN       CONFIG_ESP_MAX_STA_CONN
  22. #define WIFI_TAG "wifi softAP"
  23. //static const char *WIFI_TAG = "wifi softAP";
  24. static void wifi_event_handler(void* arg, esp_event_base_t event_base,
  25.                                     int32_t event_id, void* event_data)
  26. {
  27.     if (event_id == WIFI_EVENT_AP_STACONNECTED) {
  28.         wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
  29.         ESP_LOGI(WIFI_TAG, "station "MACSTR" join, AID=%d",
  30.                  MAC2STR(event->mac), event->aid);
  31.     } else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) {
  32.         wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
  33.         ESP_LOGI(WIFI_TAG, "station "MACSTR" leave, AID=%d",
  34.                  MAC2STR(event->mac), event->aid);
  35.     }
  36. }
  37. void wifi_init_softap(void)
  38. {
  39.     ESP_ERROR_CHECK(esp_netif_init());
  40.     ESP_ERROR_CHECK(esp_event_loop_create_default());
  41.     esp_netif_create_default_wifi_ap();
  42.     wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  43.     ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  44.     ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
  45.                                                         ESP_EVENT_ANY_ID,
  46.                                                         &wifi_event_handler,
  47.                                                         NULL,
  48.                                                         NULL));
  49.     wifi_config_t wifi_config = {
  50.         .ap = {
  51.             .ssid = EXAMPLE_ESP_WIFI_SSID,
  52.             .ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
  53.             .channel = EXAMPLE_ESP_WIFI_CHANNEL,
  54.             .password = EXAMPLE_ESP_WIFI_PASS,
  55.             .max_connection = EXAMPLE_MAX_STA_CONN,
  56.             .authmode = WIFI_AUTH_WPA_WPA2_PSK,
  57.             .pmf_cfg = {
  58.                     .required = false,
  59.             },
  60.         },
  61.     };
  62.     if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0) {
  63.         wifi_config.ap.authmode = WIFI_AUTH_OPEN;
  64.     }
  65.     ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
  66.     ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));
  67.     ESP_ERROR_CHECK(esp_wifi_start());
  68.     ESP_LOGI(WIFI_TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d",
  69.              EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS, EXAMPLE_ESP_WIFI_CHANNEL);
  70. }
  71. void app_main(void)
  72. {
  73.     //Initialize NVS
  74.     esp_err_t ret = nvs_flash_init();
  75.     if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  76.       ESP_ERROR_CHECK(nvs_flash_erase());
  77.       ret = nvs_flash_init();
  78.     }
  79.     ESP_ERROR_CHECK(ret);
  80.     ESP_LOGI(WIFI_TAG, "ESP_WIFI_MODE_AP");
  81.     wifi_init_softap();
  82.     vTaskDelay(1000 / portTICK_PERIOD_MS);
  83.    
  84.     tcpServerStart();
  85. }
复制代码
tcp_server.c
  1. /*
  2. #include <string.h>
  3. #include <sys/param.h>
  4. #include "freertos/FreeRTOS.h"
  5. #include "freertos/task.h"
  6. #include "esp_system.h"
  7. #include "esp_wifi.h"
  8. #include "esp_event.h"
  9. #include "esp_log.h"
  10. #include "nvs_flash.h"
  11. #include "esp_netif.h"
  12. #include "protocol_examples_common.h"
  13. #include "lwip/err.h"
  14. #include "lwip/sockets.h"
  15. #include "lwip/sys.h"
  16. #include <lwip/netdb.h>
  17. */
  18. #include "tcp_server.h"
  19. #define PORT                        CONFIG_EXAMPLE_PORT
  20. #define KEEPALIVE_IDLE              CONFIG_EXAMPLE_KEEPALIVE_IDLE
  21. #define KEEPALIVE_INTERVAL          CONFIG_EXAMPLE_KEEPALIVE_INTERVAL
  22. #define KEEPALIVE_COUNT             CONFIG_EXAMPLE_KEEPALIVE_COUNT
  23. #define TCP_TAG "TCP"
  24. //static const char *TCP_TAG= "example";
  25. static void do_retransmit(const int sock)
  26. {
  27.     int len;
  28.     char rx_buffer[128];
  29.     char tx_buffer[128];
  30.     do {
  31.         len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
  32.         if (len < 0) {
  33.             ESP_LOGE(TCP_TAG, "Error occurred during receiving: errno %d", errno);
  34.         } else if (len == 0) {
  35.             ESP_LOGW(TCP_TAG, "Connection closed");
  36.         } else {
  37.             rx_buffer[len] = 0; // Null-terminate whatever is received and treat it like a string
  38.             ESP_LOGI(TCP_TAG, "Received %d bytes: %s", len, rx_buffer);
  39.             // send() can return less bytes than supplied length.
  40.             // Walk-around for robust implementation.
  41.             int to_write = len;
  42.             while (to_write > 0) {
  43.                 int written = send(sock, rx_buffer + (len - to_write), to_write, 0);
  44.                 if (written < 0) {
  45.                     ESP_LOGE(TCP_TAG, "Error occurred during sending: errno %d", errno);
  46.                 }
  47.                 to_write -= written;
  48.             }
  49.         }
  50.     } while (len > 0);
  51. }
  52. static void tcp_server_task(void *pvParameters)
  53. {
  54.     char addr_str[128];
  55.     int addr_family = (int)pvParameters;
  56.     int ip_protocol = 0;
  57.     int keepAlive = 1;
  58.     int keepIdle = KEEPALIVE_IDLE;
  59.     int keepInterval = KEEPALIVE_INTERVAL;
  60.     int keepCount = KEEPALIVE_COUNT;
  61.     struct sockaddr_storage dest_addr;
  62.     if (addr_family == AF_INET) {
  63.         struct sockaddr_in *dest_addr_ip4 = (struct sockaddr_in *)&dest_addr;
  64.         dest_addr_ip4->sin_addr.s_addr = htonl(INADDR_ANY);
  65.         dest_addr_ip4->sin_family = AF_INET;
  66.         dest_addr_ip4->sin_port = htons(PORT);
  67.         ip_protocol = IPPROTO_IP;
  68.     }
  69. #ifdef CONFIG_EXAMPLE_IPV6
  70.     else if (addr_family == AF_INET6) {
  71.         struct sockaddr_in6 *dest_addr_ip6 = (struct sockaddr_in6 *)&dest_addr;
  72.         bzero(&dest_addr_ip6->sin6_addr.un, sizeof(dest_addr_ip6->sin6_addr.un));
  73.         dest_addr_ip6->sin6_family = AF_INET6;
  74.         dest_addr_ip6->sin6_port = htons(PORT);
  75.         ip_protocol = IPPROTO_IPV6;
  76.     }
  77. #endif
  78.     int listen_sock = socket(addr_family, SOCK_STREAM, ip_protocol);
  79.     if (listen_sock < 0) {
  80.         ESP_LOGE(TCP_TAG, "Unable to create socket: errno %d", errno);
  81.         vTaskDelete(NULL);
  82.         return;
  83.     }
  84.     int opt = 1;
  85.     setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  86. #if defined(CONFIG_EXAMPLE_IPV4) && defined(CONFIG_EXAMPLE_IPV6)
  87.     // Note that by default IPV6 binds to both protocols, it is must be disabled
  88.     // if both protocols used at the same time (used in CI)
  89.     setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt));
  90. #endif
  91.     ESP_LOGI(TCP_TAG, "Socket created");
  92.     int err = bind(listen_sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
  93.     if (err != 0) {
  94.         ESP_LOGE(TCP_TAG, "Socket unable to bind: errno %d", errno);
  95.         ESP_LOGE(TCP_TAG, "IPPROTO: %d", addr_family);
  96.         goto CLEAN_UP;
  97.     }
  98.     ESP_LOGI(TCP_TAG, "Socket bound, port %d", PORT);
  99.     err = listen(listen_sock, 1);
  100.     if (err != 0) {
  101.         ESP_LOGE(TCP_TAG, "Error occurred during listen: errno %d", errno);
  102.         goto CLEAN_UP;
  103.     }
  104.     while (1) {
  105.         ESP_LOGI(TCP_TAG, "Socket listening");
  106.         struct sockaddr_storage source_addr; // Large enough for both IPv4 or IPv6
  107.         socklen_t addr_len = sizeof(source_addr);
  108.         int sock = accept(listen_sock, (struct sockaddr *)&source_addr, &addr_len);
  109.         if (sock < 0) {
  110.             ESP_LOGE(TCP_TAG, "Unable to accept connection: errno %d", errno);
  111.             break;
  112.         }
  113.         // Set tcp keepalive option
  114.         setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(int));
  115.         setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &keepIdle, sizeof(int));
  116.         setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &keepInterval, sizeof(int));
  117.         setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &keepCount, sizeof(int));
  118.         // Convert ip address to string
  119.         if (source_addr.ss_family == PF_INET) {
  120.             inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr, addr_str, sizeof(addr_str) - 1);
  121.         }
  122. #ifdef CONFIG_EXAMPLE_IPV6
  123.         else if (source_addr.ss_family == PF_INET6) {
  124.             inet6_ntoa_r(((struct sockaddr_in6 *)&source_addr)->sin6_addr, addr_str, sizeof(addr_str) - 1);
  125.         }
  126. #endif
  127.         ESP_LOGI(TCP_TAG, "Socket accepted ip address: %s", addr_str);
  128.         do_retransmit(sock);
  129.         shutdown(sock, 0);
  130.         close(sock);
  131.     }
  132. CLEAN_UP:
  133.     close(listen_sock);
  134.     vTaskDelete(NULL);
  135. }
  136. void tcpServerStart(void)
  137. {
  138.     //ESP_ERROR_CHECK(nvs_flash_init());
  139.     //ESP_ERROR_CHECK(esp_netif_init());
  140.     //ESP_ERROR_CHECK(esp_event_loop_create_default());
  141.     /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  142.      * Read "Establishing Wi-Fi or Ethernet Connection" section in
  143.      * examples/protocols/README.md for more information about this function.
  144.      */
  145.     //ESP_ERROR_CHECK(example_connect());
  146. #ifdef CONFIG_EXAMPLE_IPV4
  147.     xTaskCreate(tcp_server_task, "tcp_server", 4096, (void*)AF_INET, 5, NULL);
  148. #endif
  149. #ifdef CONFIG_EXAMPLE_IPV6
  150.     xTaskCreate(tcp_server_task, "tcp_server", 4096, (void*)AF_INET6, 5, NULL);
  151. #endif
  152. }
复制代码
ATP+TCP客户端程序

主函数
  1. #include <string.h>
  2. #include <sys/param.h>
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "freertos/event_groups.h"
  6. #include "esp_system.h"
  7. #include "esp_wifi.h"
  8. #include "esp_event.h"
  9. #include "esp_log.h"
  10. #include "nvs_flash.h"
  11. #include "esp_netif.h"
  12. #include "addr_from_stdin.h"
  13. #include "lwip/err.h"
  14. #include "lwip/sockets.h"
  15. #include "my_wifi.h"
  16. #include "tcp_client.h"
  17. void app_main(void)
  18. {
  19.     //wifi conect
  20.     wifiStaStart();
  21.     //tcp client
  22.     tcpClientStart();
  23. }
复制代码
my_wifi.c
  1. #include "my_wifi.h"
  2. /* The examples use WiFi configuration that you can set via project configuration menu
  3.    If you'd rather not, just change the below entries to strings with
  4.    the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
  5. */
  6. #define EXAMPLE_ESP_WIFI_SSID      "myesp32AP"
  7. #define EXAMPLE_ESP_WIFI_PASS      "esp45678"
  8. #define EXAMPLE_ESP_MAXIMUM_RETRY  CONFIG_ESP_MAXIMUM_RETRY
  9. #if CONFIG_ESP_WIFI_AUTH_OPEN
  10. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_OPEN
  11. #elif CONFIG_ESP_WIFI_AUTH_WEP
  12. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WEP
  13. #elif CONFIG_ESP_WIFI_AUTH_WPA_PSK
  14. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA_PSK
  15. #elif CONFIG_ESP_WIFI_AUTH_WPA2_PSK
  16. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_PSK
  17. #elif CONFIG_ESP_WIFI_AUTH_WPA_WPA2_PSK
  18. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA_WPA2_PSK
  19. #elif CONFIG_ESP_WIFI_AUTH_WPA3_PSK
  20. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA3_PSK
  21. #elif CONFIG_ESP_WIFI_AUTH_WPA2_WPA3_PSK
  22. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_WPA3_PSK
  23. #elif CONFIG_ESP_WIFI_AUTH_WAPI_PSK
  24. #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WAPI_PSK
  25. #endif
  26. /* FreeRTOS event group to signal when we are connected*/
  27. static EventGroupHandle_t s_wifi_event_group;
  28. /* The event group allows multiple bits for each event, but we only care about two events:
  29. * - we are connected to the AP with an IP
  30. * - we failed to connect after the maximum amount of retries */
  31. #define WIFI_CONNECTED_BIT BIT0
  32. #define WIFI_FAIL_BIT      BIT1
  33. static const char *TAG = "wifi station";
  34. static int s_retry_num = 0;
  35. static void event_handler(void* arg, esp_event_base_t event_base,
  36.                                 int32_t event_id, void* event_data)
  37. {
  38.     if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
  39.         esp_wifi_connect();
  40.     } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
  41.         if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
  42.             esp_wifi_connect();
  43.             s_retry_num++;
  44.             ESP_LOGI(TAG, "retry to connect to the AP");
  45.         } else {
  46.             xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
  47.         }
  48.         ESP_LOGI(TAG,"connect to the AP fail");
  49.     } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
  50.         ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
  51.         ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
  52.         s_retry_num = 0;
  53.         xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
  54.     }
  55. }
  56. void wifi_init_sta(void)
  57. {
  58.     s_wifi_event_group = xEventGroupCreate();
  59.     ESP_ERROR_CHECK(esp_netif_init());
  60.     ESP_ERROR_CHECK(esp_event_loop_create_default());
  61.     esp_netif_create_default_wifi_sta();
  62.     wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  63.     ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  64.     esp_event_handler_instance_t instance_any_id;
  65.     esp_event_handler_instance_t instance_got_ip;
  66.     ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
  67.                                                         ESP_EVENT_ANY_ID,
  68.                                                         &event_handler,
  69.                                                         NULL,
  70.                                                         &instance_any_id));
  71.     ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
  72.                                                         IP_EVENT_STA_GOT_IP,
  73.                                                         &event_handler,
  74.                                                         NULL,
  75.                                                         &instance_got_ip));
  76.     wifi_config_t wifi_config = {
  77.         .sta = {
  78.             .ssid = EXAMPLE_ESP_WIFI_SSID,
  79.             .password = EXAMPLE_ESP_WIFI_PASS,
  80.             /* Authmode threshold resets to WPA2 as default if password matches WPA2 standards (pasword len => 8).
  81.              * If you want to connect the device to deprecated WEP/WPA networks, Please set the threshold value
  82.              * to WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK and set the password with length and format matching to
  83.              * WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK standards.
  84.              */
  85.             .threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD,
  86.             .sae_pwe_h2e = WPA3_SAE_PWE_BOTH,
  87.         },
  88.     };
  89.     ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
  90.     ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
  91.     ESP_ERROR_CHECK(esp_wifi_start() );
  92.     ESP_LOGI(TAG, "wifi_init_sta finished.");
  93.     /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
  94.      * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
  95.     EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
  96.             WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
  97.             pdFALSE,
  98.             pdFALSE,
  99.             portMAX_DELAY);
  100.     /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
  101.      * happened. */
  102.     if (bits & WIFI_CONNECTED_BIT) {
  103.         ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
  104.                  EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
  105.     } else if (bits & WIFI_FAIL_BIT) {
  106.         ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
  107.                  EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
  108.     } else {
  109.         ESP_LOGE(TAG, "UNEXPECTED EVENT");
  110.     }
  111. }
  112. void wifiStaStart(void)
  113. {
  114.     //Initialize NVS
  115.     esp_err_t ret = nvs_flash_init();
  116.     if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  117.       ESP_ERROR_CHECK(nvs_flash_erase());
  118.       ret = nvs_flash_init();
  119.     }
  120.     ESP_ERROR_CHECK(ret);
  121.     ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
  122.     wifi_init_sta();
  123.     //tcpStart();
  124. }
复制代码
tcp_client.c
  1. #include "tcp_client.h"
  2. #if defined(CONFIG_EXAMPLE_IPV4)
  3. #define HOST_IP_ADDR CONFIG_EXAMPLE_IPV4_ADDR
  4. #elif defined(CONFIG_EXAMPLE_IPV6)
  5. #define HOST_IP_ADDR CONFIG_EXAMPLE_IPV6_ADDR
  6. #else
  7. #define HOST_IP_ADDR ""
  8. #endif
  9. #define PORT CONFIG_EXAMPLE_PORT
  10. static const char *TAGC = "example";
  11. static const char *payload = "Message from Client1:tem,hum,c2h4 ";
  12. static void tcp_client_task(void *pvParameters)
  13. {
  14.     char rx_buffer[128];
  15.     char host_ip[] = HOST_IP_ADDR;
  16.     int addr_family = 0;
  17.     int ip_protocol = 0;
  18.     while (1) {
  19. #if defined(CONFIG_EXAMPLE_IPV4)
  20.         struct sockaddr_in dest_addr;
  21.         dest_addr.sin_addr.s_addr = inet_addr(host_ip);
  22.         dest_addr.sin_family = AF_INET;
  23.         dest_addr.sin_port = htons(PORT);
  24.         addr_family = AF_INET;
  25.         ip_protocol = IPPROTO_IP;
  26. #elif defined(CONFIG_EXAMPLE_IPV6)
  27.         struct sockaddr_in6 dest_addr = { 0 };
  28.         inet6_aton(host_ip, &dest_addr.sin6_addr);
  29.         dest_addr.sin6_family = AF_INET6;
  30.         dest_addr.sin6_port = htons(PORT);
  31.         dest_addr.sin6_scope_id = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE);
  32.         addr_family = AF_INET6;
  33.         ip_protocol = IPPROTO_IPV6;
  34. #elif defined(CONFIG_EXAMPLE_SOCKET_IP_INPUT_STDIN)
  35.         struct sockaddr_storage dest_addr = { 0 };
  36.         ESP_ERROR_CHECK(get_addr_from_stdin(PORT, SOCK_STREAM, &ip_protocol, &addr_family, &dest_addr));
  37. #endif
  38.         int sock =  socket(addr_family, SOCK_STREAM, ip_protocol);
  39.         if (sock < 0) {
  40.             ESP_LOGE(TAGC, "Unable to create socket: errno %d", errno);
  41.             break;
  42.         }
  43.         ESP_LOGI(TAGC, "Socket created, connecting to %s:%d", host_ip, PORT);
  44.         int err = connect(sock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in6));
  45.         if (err != 0) {
  46.             ESP_LOGE(TAGC, "Socket unable to connect: errno %d", errno);
  47.             break;
  48.         }
  49.         ESP_LOGI(TAGC, "Successfully connected");
  50.         while (1) {
  51.             int err = send(sock, payload, strlen(payload), 0);
  52.             if (err < 0) {
  53.                 ESP_LOGE(TAGC, "Error occurred during sending: errno %d", errno);
  54.                 break;
  55.             }
  56.             int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
  57.             // Error occurred during receiving
  58.             if (len < 0) {
  59.                 ESP_LOGE(TAGC, "recv failed: errno %d", errno);
  60.                 break;
  61.             }
  62.             // Data received
  63.             else {
  64.                 rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
  65.                 ESP_LOGI(TAGC, "Received %d bytes from %s:", len, host_ip);
  66.                 ESP_LOGI(TAGC, "%s", rx_buffer);
  67.             }
  68.             vTaskDelay(2000 / portTICK_PERIOD_MS);
  69.         }
  70.         if (sock != -1) {
  71.             ESP_LOGE(TAGC, "Shutting down socket and restarting...");
  72.             shutdown(sock, 0);
  73.             close(sock);
  74.         }
  75.     }
  76.     vTaskDelete(NULL);
  77. }
  78. void tcpClientStart(void)
  79. {
  80.    // ESP_ERROR_CHECK(nvs_flash_init());
  81.    // ESP_ERROR_CHECK(esp_netif_init());
  82.    // ESP_ERROR_CHECK(esp_event_loop_create_default());
  83.     /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  84.      * Read "Establishing Wi-Fi or Ethernet Connection" section in
  85.      * examples/protocols/README.md for more information about this function.
  86.      */
  87.    // ESP_ERROR_CHECK(example_connect());
  88.     xTaskCreate(tcp_client_task, "tcp_client", 4096, NULL, 5, NULL);
  89. }
复制代码
注意

需要在Kconfig.projbuild文件中预先进行一些配置如IP,端口号等。CMakeLists.txt需要包含主函数调用的所有c文件。
结果

成功通信运行的结果如下图所示
服务端运行

客户端运行


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

熊熊出没

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表