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 Client Communication Model2.2 Configuration Parameters2.3 Core API2.4 Command Set3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Explained5.1 Configuration Area5.2 Creating the Socket and Connecting5.3 Sending and Receiving Data5.4 Command Dispatch5.5 Main Loop6. Operating Procedures6.1 Environment Preparation6.2 Flashing and Running6.3 Serial Output Example6.4 Verification Methods7. Common Problems


1. TCP Client Overview

TCP (Transmission Control Protocol) is a connection-oriented reliable transport protocol that guarantees in-order arrival and no packet loss. In this experiment the ESP32-S3 acts as a TCP client, connecting to the network debugging assistant (in TCP Server mode) on the PC to achieve bidirectional send/receive: the client can receive commands from the PC and reply (such as TIME / INFO / PING), while periodically sending heartbeat packets to maintain the connection.

Typical application scenarios:

Application TypeExample
Remote controlPhone/PC sends commands to control ESP32 peripherals
Data reportingSensors push data to a server periodically
File transferFirmware OTA upgrade
Chat communicationSimple TCP chat terminal

The PC needs to run a TCP Server (such as the NetAssist network debugging assistant) listening on a specified port, waiting for the ESP32 to connect.


2. Core Concepts

2.1 TCP Client Communication Model

┌──────────┐    TCP connection   ┌──────────┐
│ ESP32-S3 │ ── connect() →      │   PC     │
│ (Client) │ ←── bidirectional ─→│ (Server) │
└──────────┘                     └──────────┘
  • TCP is connection-oriented; you must connect() to establish a connection before communicating
  • After the connection is established, both sides can send() / recv()
  • If either side calls close() or loses the network, the connection is broken and reconnection is needed

2.2 Configuration Parameters

ParameterDescriptionValue Used in This Experiment
WIFI_SSID / WIFI_PASSWiFi connection"Yahboom2" / "yahboom890729"
SERVER_IPPC IP (server address)192.168.11.183
SERVER_PORTPort the PC is listening on8080
HEARTBEAT_INTERVALHeartbeat interval10s
RECONNECT_INTERVALDisconnect reconnect interval5s

2.3 Core API

​x
import socket
​
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # TCP socket
sock.connect(("192.168.11.183", 8080))           # connect to server
sock.sendall(b"hello")                           # send data
data = sock.recv(512)                            # receive (up to 512 bytes)
sock.close()                                     # close

2.4 Command Set

The PC sends the following text commands through the network assistant; the ESP32 receives them and dispatches them in process_command():

CommandFunctionReply Content
PINGConnectivity checkPONG
TIMEQuery runtime statusRuntime (s) + free memory (KB)
INFOQuery device infoFree memory + total memory + usage + Flash capacity
OtherEchoReceived: {original message}

Command matching is case-sensitive; ping is not recognized as PING. Commands do not contain leading/trailing spaces (recv performs a strip()).


3. Hardware Dependencies

The ESP32-S3 has built-in WiFi. A PC running the network debugging assistant (in TCP Server mode, listening on SERVER_PORT) is needed, on the same LAN as the ESP32-S3.


4. Project Architecture and Flow

xxxxxxxxxx
Script execution (single-file .py)
  |
  |- wifi_connect(): connect to WiFi (STA mode)
  |- create_socket() / connect_server(): create socket -> connect to PC
  |
  |- while True:
       |- recv_msg(): non-blocking reception of PC commands
       |- process_command(): command dispatch (TIME/INFO/PING)
       |- send_msg(): reply with processing results
       |- heartbeat: send HEARTBEAT every 10s

5. Source Code Explained

Full source code: Source Code -> MicroPython -> 4.Network Protocols -> TCP_Client -> TCP_Client.py

5.1 Configuration Area

The server IP and port, heartbeat interval, and reconnect interval can all be modified as needed.

xxxxxxxxxx
SERVER_IP   = "192.168.11.183"   # PC IP
SERVER_PORT = 8080              # PC listen port
HEARTBEAT_INTERVAL = 10         # heartbeat interval (s)
RECONNECT_INTERVAL = 5          # reconnect interval (s)

5.2 Creating the Socket and Connecting

socket.SOCK_STREAM = TCP; settimeout(5) prevents recv from blocking indefinitely.

xxxxxxxxxx
def create_socket():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # TCP socket
    sock.settimeout(5)
    return sock
​
def connect_server(sock, ip, port):
    sock.connect((ip, port))                     # connect
    print(f"[TCP] Connected to server {ip}:{port}")

5.3 Sending and Receiving Data

sendall ensures the data is sent completely; an empty byte string returned by recv means the peer has closed the connection.

xxxxxxxxxx
def send_msg(sock, msg):
    data = msg.encode("utf-8") if isinstance(msg, str) else msg
    sock.sendall(data)                           # send all
​
def recv_msg(sock, buf_size=512):
    data = sock.recv(buf_size)                   # blocking receive
    if data:
        return data.decode("utf-8")
    else:
        return None  # connection closed

5.4 Command Dispatch

Supports TIME (runtime status), INFO (device info), and PING (replies PONG); all other messages are echoed as-is.

xxxxxxxxxx
def process_command(msg):
    if msg == "TIME":
        return f"uptime: {uptime:.0f}s, Free memory: {free / 1024:.0f} KB"
    elif msg == "INFO":
        return f"ESP32-S3 Client, Free memory: {gc.mem_free() / 1024:.0f} KB"
    elif msg == "PING":
        return "PONG"
    else:
        return f"Received: {msg}"                    # echo

5.5 Main Loop

Auto-reconnect on disconnect + receive command processing + send heartbeat every 10s.

xxxxxxxxxx
while True:
    if sock is None:                              # reconnect if needed
        sock = create_socket()
        if not connect_server(sock, SERVER_IP, SERVER_PORT):
            sock = None; time.sleep(RECONNECT_INTERVAL)
            continue
​
    msg = recv_msg(sock)
    if msg:
        reply = process_command(msg)
        if reply:
            send_msg(sock, reply)
​
    if time.time() - last_heartbeat > HEARTBEAT_INTERVAL:  # heartbeat
        send_msg(sock, "HEARTBEAT")
        last_heartbeat = time.time()

6. Operating Procedures

6.1 Environment Preparation

Thonny IDE steps: See MicroPython -> 1. Before Development -> 3.Thonny IDE.

  1. Open the network debugging assistant 网络调试助手图标on the PC, select TCP Server mode, and set the listen port to 8080

    网络调试助手设置

  2. Confirm the PC IP (ipconfig) and modify SERVER_IP in the code

  3. Confirm the ESP32-S3 and the PC are on the same WiFi

6.2 Flashing and Running

  1. Open TCP_Client.py in Thonny IDE, modify WIFI_SSID, WIFI_PASS, SERVER_IP, and SERVER_PORT

    用户配置区

  2. Click Run

6.3 Serial Output Example

xxxxxxxxxx
===== ESP32-S3 TCP Client =====
[WiFi] Connecting to 'Yahboom2' ...
[WiFi] Connected! IP: 192.168.11.229
[TCP] Connected to server 192.168.11.27:8080
[Sent] HEARTBEAT
[Recv] TIME
[Sent] ESP32-S3 status
  uptime: 3320s
  Free memory: 8119 KB
[Sent] HEARTBEAT
[Recv] INFO
[Sent] ESP32-S3 Client
  Free memory: 8117 KB
  Total memory:   8127 KB
  utilization:   0.1%
  Flash:    16 MB
[Recv] PING
[Sent] PONG
[Sent] HEARTBEAT

串口打印

6.4 Verification Methods

OperationExpected Result
PC sends PINGESP32 replies PONG
PC sends TIMEESP32 replies runtime + free memory
PC sends INFOESP32 replies memory + Flash info
PC closes the ServerESP32 reconnects every 5s
Wait 10sESP32 automatically sends HEARTBEAT

7. Common Problems

SymptomCauseSolution
Connection fails ECONNREFUSEDPC Server not started or wrong portConfirm the network assistant has started a TCP Server with port=8080
Connection timeoutIP not on the same subnet or firewall blockingping the PC IP to test reachability, disable the firewall
Cannot receive PC messagesrecv() blocking causes heartbeat to stopAlready using settimeout(0.5) non-blocking polling
Garbled Chinese charactersInconsistent encodingUse UTF-8 encoding/decoding uniformly
UDP Server 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

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文