首页 > 解决方案 > ESP 32 TCP 连接被对等方关闭

问题描述

我正在开发一个基于使用 3 个嗅探 PROBE 数据包的 ESP32 板跟踪运动的项目。以顺序方式为每个 ESP 调用此函数。所以首先我连接所有的 ESP,然后调用这个函数并开始从连接中读取数据包的数量,然后是每个数据包。问题是,当我尝试从每个 ESP 发送 200 个数据包的列表时,服务器正确接收到第一个 ESP 的数据包数量,但随后开始读取数据包并仅接收其中的一小部分(正确接收大约 200 个数据包中的 140 个)全部,然后是数据包的一部分 141),然后崩溃。主板能够发送所有数据包,但由于崩溃,因此无法从服务器接收任何 ACK。我可以'

int recvPseq(SOCKET s) {

  uint32_t numP;
  unsigned char netP[4];
  int res;

  res = recv(s, (char *)netP, 4, 0);
  if (res > 0) {
    if (res != 4) {
      cout << "Number of packet not entirely received! Only: " << res << " bytes" << endl;
      return 0;
    }
  }
  else if (res == 0) {
    cout << "Socket closed by the client" << endl;
    return 0;
  }
  else {
    cout << "Error while receving the number of packets: " << WSAGetLastError() << endl;
    return 0;
  }

  /* NumP contains the number of packets */
  numP = ntohl(*(uint32_t*)netP);
  cout << "Number of packets: " << numP << endl;

  /* Reading the packets */
  for (int i = 0; i < numP; i++) {

    unsigned char recvbuffer[55];

    res = recv(s, (char *)recvbuffer, 55, 0);
    if (res > 0) {
      if (res != 55) {
        cout << "Packet " << i + 1 << " not entirely received! Only: " << res << " bytes" << endl;
        return 0;
      }
    }
    else if (res == 0) {
      cout << "Socket closed by the client" << endl;
      return 0;
    }
    else {
      cout << "Error while receving the number of packets: " << WSAGetLastError() << endl;
      return 0;
    }

    cout << "Received " << i + 1 << endl;
  }
  return 1;
}

标签: c++socketstcpesp32

解决方案


您没有从 TCP 套接字正确读取。调用recv(buflen=X)可能会返回 0..X 个字节。recv()不会等到整个缓冲区都填满数据。

通常recv()必须在循环中调用,直到接收到足够的数据。每个 TCP 接收器(服务器或客户端)都必须这样做。没有办法解决这个问题。这就是 TCP 的工作原理。TCP 总是面向字节的。没有数据包边界。recv()在查看每次调用实际接收的字节数时,您将观察到网络基础设施和路径上使用的缓冲区的各种工件。


推荐阅读