Page 1 of 1

tcp_client例程为何去掉发送后,一直接收就会容易出现数据粘包

Posted: Fri Apr 01, 2022 3:05 pm
by fatcatLA

Code: Select all

while (1) {
            //int err = send(sock, payload, strlen(payload), 0);
           // if (err < 0) {
             //   ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
             //   break;
           // }

            int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
            // Error occurred during receiving
            if (len < 0) {
                ESP_LOGE(TAG, "recv failed: errno %d", errno);
                break;
            }
            // Data received
            else {
                rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
                ESP_LOGI(TAG, "Received %d bytes from %s:", len, host_ip);
                ESP_LOGI(TAG, "%s", rx_buffer);
            }

            vTaskDelay(2000 / portTICK_PERIOD_MS);
        }
代码如下,当我使用tcp_client例程,并且把发送数据注释掉,再接收数据就很容易出现TCP数据粘包,求助
[22:43:18.320]收←◆[0;32mI (13311) example: 00 02 00 00 00 06 01 01 00 00 00 0A[0m

[22:43:18.570]收←◆[0;32mI (13561) example: 00 02 00 00 00 06 01 01 00 00 00 0A[0m

[22:43:18.822]收←◆[0;32mI (13811) example: 00 02 00 00 00 06 01 01 00 00 00 0A00 02 00 00 00 06 01 01 00 00 00 0A[0m

[22:43:19.070]收←◆[0;32mI (14061) example: 00 02 00 00 00 06 01 01 00 00 00 0A[0m

[22:43:19.322]收←◆[0;32mI (14311) example: 00 02 00 00 00 06 01 01 00 00 00 0A[0m

Re: tcp_client例程为何去掉发送后,一直接收就会容易出现数据粘包

Posted: Mon May 09, 2022 9:04 am
by ESP_YJM
这两者应该没有直接的关联,TCP 粘包总是会存在的。你可以启用 socket option TCP_NODELAY 来避开 TCP 粘包