esp32 tcp socket客户端收发代码

#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <string.h>
#include "esp_timer.h"
#include "esp_sleep.h"
#include <unistd.h>

#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"
#include "lwip/sockets.h"

#define EXAMPLE_ESP_WIFI_SSID "hehui2"
#define EXAMPLE_ESP_WIFI_PASS "123456789"

#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

#define HOST_IP_ADDR "192.168.43.30"
#define PORT 8080

static EventGroupHandle_t s_wifi_event_group;

static int s_retry_num = 0 ;

static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
	if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
	        esp_wifi_connect();
	    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
	        if (s_retry_num < 10000) {
	            esp_wifi_connect();
	            s_retry_num++;
	            printf("retry to connect to the AP\n");
	        } else {
	            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
	        }
	        printf("connect to the AP fail\n");
	    }
}

static void got_ip_event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
 if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
	        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
	        printf("got ip:" IPSTR "\n", IP2STR(&event->ip_info.ip));
	        s_retry_num = 0;
	        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
	    }
}

static const char *payload = "Message from ESP32 ";

static void tcp_client_task(void *pvParameters)
{
	char rx_buffer[128];
	    char host_ip[] = HOST_IP_ADDR;
	    int addr_family = 0;
	    int ip_protocol = 0;

while(1){
	 struct sockaddr_in dest_addr;
	        dest_addr.sin_addr.s_addr = inet_addr(host_ip);
	        dest_addr.sin_family = AF_INET;
	        dest_addr.sin_port = htons(PORT);
	        addr_family = AF_INET;
	        ip_protocol = IPPROTO_IP;
	        int sock =  socket(addr_family, SOCK_STREAM, ip_protocol);
	               if (sock < 0) {
	            	   printf("Unable to create socket: errno %d", errno);
	                   break;
	               }
	              printf("Socket created, connecting to %s:%d", host_ip, PORT);
	               int err = connect(sock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in6));
	               if (err != 0) {
	            	   printf("Socket unable to connect: errno %d", errno);
	                   break;
	               }
	               printf("Successfully connected");
	               while(1){
	            	   int err = send(sock, payload, strlen(payload), 0);
	            	              if (err < 0) {
	            	            	  printf("Error occurred during sending: errno %d", errno);
	            	                  break;
	            	              }
	            	              int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
	            	                             rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
	            	                             printf("%s\n", rx_buffer);
//	            	                         }
	            	   sleep(1);
	               }

}

}

void wifi_init_sta(){
	s_wifi_event_group = xEventGroupCreate();

	    ESP_ERROR_CHECK(esp_netif_init());

	    ESP_ERROR_CHECK(esp_event_loop_create_default());
	    esp_netif_create_default_wifi_sta();

	    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
	    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

	    esp_event_handler_instance_t instance_any_id;
	    esp_event_handler_instance_t instance_got_ip;
	    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
	                                                        ESP_EVENT_ANY_ID,
	                                                        &event_handler,
	                                                        NULL,
	                                                        &instance_any_id));
	    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
	                                                        IP_EVENT_STA_GOT_IP,
	                                                        &got_ip_event_handler,
	                                                        NULL,
	                                                        &instance_got_ip));

	    wifi_config_t wifi_config = {
	        .sta = {
	            .ssid = EXAMPLE_ESP_WIFI_SSID,
	            .password = EXAMPLE_ESP_WIFI_PASS,
	            /* Authmode threshold resets to WPA2 as default if password matches WPA2 standards (pasword len => 8).
	             * If you want to connect the device to deprecated WEP/WPA networks, Please set the threshold value
	             * to WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK and set the password with length and format matching to
		     * WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK standards.
	             */
	            .threshold.authmode = WIFI_AUTH_OPEN,
	            .sae_pwe_h2e = WPA3_SAE_PWE_BOTH,
	        },
	    };
	    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
	    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
	    ESP_ERROR_CHECK(esp_wifi_start() );

//	    ESP_LOGI(TAG, "wifi_init_sta finished.");

	    /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
	     * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
	    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
	            WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
	            pdFALSE,
	            pdFALSE,
	            portMAX_DELAY);

	    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
	     * happened. */
	    if (bits & WIFI_CONNECTED_BIT) {
	    	printf("connected to ap SSID\n");
	    	xTaskCreate(tcp_client_task, "tcp_client", 4096, NULL, 5, NULL);
	    } else if (bits & WIFI_FAIL_BIT) {
	    	printf("Failed to connect to SSID\n");
	    } else {
	    	printf("UNEXPECTED EVENT\n");
	    }
}

void app_main(void) {
	    esp_err_t ret = nvs_flash_init();
	    ESP_ERROR_CHECK(ret);
	    wifi_init_sta();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值