yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

Welcome to ESP32 Core Board repository

6. TCP Client Experiment

TCP Client Experiment


TCP Client Experiment1. TCP Client Overview2. Core Concepts2.1 TCP Connection Lifecycle2.2 The "Packet Sticking" Problem of Stream Protocols2.3 write() vs print()3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Analysis5.1 Configuration and Global Variables5.2 setup() — Establish TCP Connection5.3 loop() — Send and Receive6. Operation Flow6.1 Build and Flash6.2 Operation Steps6.3 Verification Methods7. Common Issues


1. TCP Client Overview

TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte-stream transport layer protocol. It establishes connections through three-way handshake, ensuring data arrives in order and intact.

TCP is the foundation of IoT communication. Whether it's HTTP web requests, MQTT message publishing, OTA firmware upgrades, or database remote connections, they all rely on TCP's reliable transmission at the underlying layer. In industrial automation, smart home, and remote monitoring scenarios, devices report sensor data and receive control commands, requiring "no data loss, no order disruption" - this is TCP's core value. UDP is fast but unreliable; TCP's three-way handshake overhead is worth it for the end-to-end acknowledgment and retransmission mechanism, which is irreplaceable in most IoT scenarios.

In this experiment, ESP32-S3 acts as a TCP client to actively connect to the server, sending one data message per second and receiving server responses. The WiFiClient class encapsulates lwIP's TCP socket, with connection, sending, receiving, and disconnection detection all completed through simple method calls.

Typical Application Scenarios:

Application TypeExample
HTTP RequestsBrowser accessing web pages (HTTP is essentially TCP at the underlying layer)
Remote ControlSSH, Telnet remote terminals
Data CollectionReliable sensor data upload
File TransferFTP, custom binary protocols

2. Core Concepts

2.1 TCP Connection Lifecycle

A TCP client goes through 5 phases from connection to closure, each corresponding to a WiFiClient method:

xxxxxxxxxx
connect(ip, port)     establish connection
   ↓   underlying: three-way handshake SYN → SYN-ACK → ACK, blocking wait, returns true on success
write / print         send data
   ↓   full-duplex: both parties can send/receive simultaneously, write sends raw bytes, print sends formatted text
available() / read()  receive data
   ↓   available() returns number of readable bytes, non-blocking, returns 0 if no data
connected()           liveness check
   ↓   returns false if remote endpoint has closed (received FIN/RST) or network timeout
stop()                close connection
      underlying: four-way handshake FIN → ACK ← FIN → ACK, release socket resources
MethodFunctionBlocking?
connect(ip, port)Initiate three-way handshake, establish TCP connectionYes
write(buf, len)Send raw bytesNo (writes to send buffer)
print(str)Send formatted textNo
available()Query number of readable bytes in receive bufferNo
read(buf, len)Read data from receive bufferNo
connected()Check if connection is aliveNo
stop()Actively close connection (four-way handshake)No

2.2 The "Packet Sticking" Problem of Stream Protocols

TCP is a stream (Stream) protocol, unlike UDP which preserves message boundaries. If the sender does two write("Hello") and write("World"), the receiver may receive "HelloWorld" in one read() (packet sticking), or may receive three fragments "Hel", "loWor", "ld" (fragmentation). The application layer must define message boundaries itself (such as newline characters, length prefixes, etc.).

2.3 write() vs print()

FunctionPurposeApplicable Scenario
write(buf, len)Send raw bytesBinary protocols
print(data)Formatted text (numbers → strings)HTTP, text protocols
println(data)print + \r\n at endHTTP line endings

3. Hardware Dependencies

Pure software experiment. Need to connect to router via WIFI-STA first, client and server must be on the same local area network.


4. Project Architecture and Flow

xxxxxxxxxx
setup()
  ├─ connectWiFi()
  └─ client.connect(SERVER_IP, SERVER_PORT)  // three-way handshake

loop()
  ├─ if disconnected → stop() → mark for reconnect
  ├─ client.write(send_buf)                   // send raw bytes
  ├─ if client.available() → client.read()    // non-blocking read
  └─ delay(1000)

5. Source Code Analysis

Complete source code: Source code → Arduino → 3.Network Communication → TCP_Client → TCP_Client.ino

5.1 Configuration and Global Variables

xxxxxxxxxx
#include <WiFi.h>
WiFiClient client;
const char* SERVER_IP = "192.168.11.183";
uint16_t    SERVER_PORT = 8080;

5.2 setup() — Establish TCP Connection

client.connect() initiates three-way handshake, returns true on success, returns false on failure (server not listening/firewall rejection).

xxxxxxxxxx
void setup() {
  Serial.begin(115200);
  connectWiFi();

  if (!client.connect(SERVER_IP, SERVER_PORT)) {
    Serial.println("Failed to connect to the server!");
    return;
  }
  Serial.println("Server Connected Successfully!");
}

5.3 loop() — Send and Receive

xxxxxxxxxx
void loop() {
  if (!client.connected()) {        // detect disconnection
    Serial.println("TCP Server disconnected!");
    client.stop();
    delay(2000);
    ESP.restart();
    return;
  }

  client.write("ESP32 TCP Client Data");  // send raw bytes

  if (client.available()) {               // non-blocking read
    char buf[128];
    int len = client.read(buf, sizeof(buf) - 1);
    buf[len] = '\0';
    Serial.printf("Receive: %s\n", buf);
  }
  delay(1000);
}

client.connected() returns false when: server FIN received, RST received, or multiple retransmissions with no ACK timeout. ESP.restart() is used for overall reset and reconnect after disconnection—this is the cleanest approach.


6. Operation Flow

6.1 Build and Flash

Arduino flash process: See Arduino → 1. Before Development → 2. Build and Flash.

  1. Modify server IP to actual address

  2. First use network debugging assistant or TCP server program to listen on port 8080

  3. Build and flash

6.2 Operation Steps

Step 1: Open network debugging assistant网络调试助手图标, configure TCP server

Open network debugging assistant on PC, configure with following parameters:

Network debugging assistant settings

ParameterValue
Protocol TypeTCP Server
Local IP AddressPC's LAN IP (e.g., 192.168.11.183)
Local Port8080

Click "Connect" button, network debugging assistant starts listening on TCP port 8080.

Step 2: Modify server IP in code, flash program

Open Arduino IDE, modify SERVER_IP in code to PC's actual LAN IP address, then compile and flash to ESP32-S3 development board.

Modify IP

Step 3: Open serial monitor, observe connection and send/receive

After flashing, open serial monitor (baud rate 115200), ESP32 will automatically connect to TCP server, after successful connection sends one data message per second and receives replies:

xxxxxxxxxx
11:30:16.823 -> Connecting to WiFi: Yahboom2 (Attempt 1)
11:30:17.877 -> ...
11:30:18.885 -> WiFi Connected successfully!
11:30:18.885 -> Device IP: 192.168.11.229
11:30:18.885 -> Target Server: 192.168.11.183:8080
11:30:18.930 -> Server Connected Successfully!
11:30:18.930 -> Send data: ESP32 TCP Client Data
11:30:19.942 -> Send data: ESP32 TCP Client Data
11:30:20.950 -> Send data: ESP32 TCP Client Data
...

Serial monitor

At this point, enter any content in the send area of network debugging assistant and send, serial monitor will print data received by ESP32.

Network debugging assistant print

Data interaction:

Data interaction

Step 4: Test disconnection detection

Close TCP server of network debugging assistant (click "Disconnect"). After ESP32 detects disconnection, it prints TCP Server disconnected!, automatically restarts after 2 seconds and attempts to reconnect.

Disconnect

6.3 Verification Methods

OperationExpected Result
Power on when server is onlineConnection successful, send/receive once per second
Disconnect serverPrint "disconnected", ESP.restart() resets and reconnects

7. Common Issues

SymptomCauseSolution
connect() never returnsFirewall drops SYN packet with no responseCheck server firewall settings
Received data stuck togetherInherent characteristic of TCP stream protocolAdd message boundary at application layer (e.g., \n separator)
connected() returns true but write failsConnection closed but not detected (half-open connection)Enable TCP keepalive or periodic heartbeat
UDP Client Experiment
TCP Server Experiment

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文