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

fatcatLA
Posts: 2
Joined: Sat Mar 12, 2022 3:17 am

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

Postby fatcatLA » Fri Apr 01, 2022 3:05 pm

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

ESP_YJM
Posts: 300
Joined: Fri Feb 26, 2021 10:30 am

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

Postby ESP_YJM » Mon May 09, 2022 9:04 am

这两者应该没有直接的关联,TCP 粘包总是会存在的。你可以启用 socket option TCP_NODELAY 来避开 TCP 粘包

Who is online

Users browsing this forum: No registered users and 40 guests