ESP32 TCP客户端

ESP32 TCP client

我想在 windows 上设置 TCP 服务器,在 ESP32 上设置 TCP 客户端。主要想法是将字符串发送到 ESP32,更改它并将其发送回服务器,但我对所有这些东西都很陌生,并且一直坚持在 ESP32 上设置 TCP 客户端。示例或参考资料会很有帮助。

你如何与你的 ESP 沟通?如果你通过UART通信,只需在UART端口上写入他需要的AT命令给他:

"AT+CIPSTATUS\r\n" 然后等待他的回应。

如果你的电脑是直接连ESP32的,直接用putty直接发送AT命令就可以了

可在此处找到 AT 命令的非详尽列表: https://www.espressif.com/sites/default/files/documentation/esp32_at_instruction_set_and_examples_en.pdf

int create_ipv4_socket()
{
  struct addrinfo hints;
  struct addrinfo *res;
  struct in_addr *addr;

  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  int err = getaddrinfo(UDP_IPV4_ADDR, TCP_PORT, &hints, &res);

  if(err != 0 || res == NULL) {
    printf("DNS lookup failed err=%d res=%p\n", err, res);
    return -1;
  }

  /* Code to print the resolved IP.

     Note: inet_ntoa is non-reentrant, look at ipaddr_ntoa_r for "real" code */
  addr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
  printf("DNS lookup succeeded. IP=%s\n", inet_ntoa(*addr));

  l_sock = socket(res->ai_family, res->ai_socktype, 0);
  if(l_sock < 0) {
    printf("... Failed to allocate socket.\n");
    freeaddrinfo(res);
    return -1;
  }

  struct timeval to;
  to.tv_sec = 2;
  to.tv_usec = 0;
  setsockopt(l_sock,SOL_SOCKET,SO_SNDTIMEO,&to,sizeof(to));

  if(connect(l_sock, res->ai_addr, res->ai_addrlen) != 0) {
    printf("... socket connect failed errno=%d\n", errno);
    close(l_sock);
    freeaddrinfo(res);
    return -1;
  }

  printf("... connected\n");
  freeaddrinfo(res);

  // All set, socket is configured for sending and receiving
  return l_sock;
}

来自本论坛https://www.esp32.com/viewtopic.php?t=5965