一、esp32 tcp 客户端使用步骤
1、创建一个套接字描述符 使用socket(AF_INET, SOCK_STREAM ,0)函数
2、设置本地端口等 使用bind(tcpsock,(struct sockaddr *)&Loacl_addr,sizeof(Loacl_addr));
3、连接server 使用connect(tcpsock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
4、发送数据 使用send(tcpsock, "tcp test", strlen("tcp test"), 0);
5、接收服务器的数据 使用recv(tcpsock, rx_buffer, sizeof(rx_buffer) - 1, 0);
二、详细代码
#include
#include
#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_log.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include
#define HOST_IP_ADDR "192.168.43.95"
#define PORT 12345
int tcpsock = 0;
struct sockaddr_in dest_addr;
TaskHandle_t xtcpRecvTask = NULL;
void tcp_recv_data(void *pvParameters){
uint8_t rx_buffer[1024] = {0};
printf("create tcp recv\n");
int err = send(tcpsock, "tcp test", strlen("tcp test"), 0);
if (err < 0) {
printf( "Error occurred during sending: errno %d", errno);
return;
}
printf("Message sent");
while (1)
{
int len = recv(tcpsock, rx_buffer, sizeof(rx_buffer) - 1, 0);
if(len > 0){
rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
printf("Received %d bytes from %s:\n", len, rx_buffer);
int err = send(tcpsock, rx_buffer, len, 0);
if (err < 0) {
printf( "Error occurred during sending: errno %d", errno);
return;
}
printf("Message sent");
}
}
}
void tcp_ini_client(void){
tcpsock = socket(AF_INET, SOCK_STREAM ,0);
printf("sock:%d\n",tcpsock);
if(tcpsock < 0){
printf( "Unable to create socket: errno %d", errno);
return;
}
printf("Socket created, sending to %s:%d", HOST_IP_ADDR, PORT);
dest_addr.sin_addr.s_addr = inet_addr(HOST_IP_ADDR);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
struct sockaddr_in Loacl_addr; //设置本地端口
Loacl_addr.sin_addr.s_addr = htonl(INADDR_ANY);
Loacl_addr.sin_family = AF_INET;
Loacl_addr.sin_port = htons(54321);
uint8_t res = 0;
res = bind(tcpsock,(struct sockaddr *)&Loacl_addr,sizeof(Loacl_addr));
if(res != 0){
printf("bind error\n");
}
int err = connect(tcpsock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
if (err != 0) {
printf( "Socket unable to connect: errno %d", errno);
return;
}
printf( "Successfully connected\n");
xTaskCreate(&tcp_recv_data,"tcp_recv_data",2048*2,NULL,10,&xtcpRecvTask);
}
三、测试结果
流程和UDP 的是一样的 开始client发送一个字符串 然后等待接收服务器的数据并且把接收到的数据原路返回