W55RP20-EVB-MKR Module MicroPython Practice (4) - TCP Server Communication
This is the 4th article in the WIZnet W55RP20 chip MicroPython tutorial series, written based on the latest official firmware.
COMPONENTS
PROJECT DESCRIPTION
W55RP20-EVB-MKR Module MicroPython Practice (4) - TCP Server Communication
This is the 4th article in the WIZnet W55RP20 chip MicroPython tutorial series, written based on the latest official firmware. All code has been practically verified and can be directly flashed and run.Copyright Notice: This is an original technical article by WIZnet. Please indicate the source when reprinting.
Preface
In the previous practical tutorial, we completed the TCP Client communication for the W55RP20-EVB-MKR, where the development board can actively connect to the TCP Server on the computer, and complete data reception and echo.
This article will introduce TCP Server Communication. After the development board obtains an IP address via DHCP, it will create a TCP Server and listen on a specified port. The computer's SocketTester acts as a TCP Client to actively connect to the development board. After sending test data, the development board will receive the data and send back a response.
TCP Server is commonly used in scenarios such as local device listening, host computer active connection, local area network control, and debugging tool access.
The W55RP20 integrates a hardware TCP/IP protocol stack, and combined with MicroPython's socket interface, the development board can quickly implement TCP Server functionality. Developers do not need to manually handle low-level TCP protocol details, and only need to focus on application-layer logic such as socket creation, binding, listening, accepting connections, and data sending/receiving.
After reading this article, you will master:
The basic relationship between TCP Server and TCP Client
How to have the W55RP20-EVB-MKR listen on a port as a TCP Server
How to use SocketTester on the computer as a TCP Client to connect to the development board
How to receive data sent from the computer
How to send back data through TCP Server
Common troubleshooting methods when TCP Server communication fails
Series Tutorial Learning Path
This series consists of 16 articles, progressively covering the full process from basic networking to industrial-grade applications:
Article 1: Static IP Configuration and Network Basics
Article 2: DHCP Automatic Networking and Network Diagnostics
Article 3: TCP Client Communication
Article 4: TCP Server Communication (This Article)
Article 5: UDP Unicast Data Communication
Article 6: UDP Multicast/Broadcast Data Communication
Article 7: DNS Domain Name Resolution
Article 8: NTP - Getting Time from the Network
Article 9: HTTP Client Requests
Article 10: HTTP Server Setup
Article 11: HTTP Protocol and OneNET Platform Data Cloud Upload
Article 12: MQTT Protocol Basic Communication Verification
Article 13: MQTT Protocol Integration with Alibaba Cloud Platform
Article 14: MQTT Protocol Integration with OneNET Platform
Article 15: MQTT Protocol Integration with ThingSpeak Platform
Article 16: Modbus Industrial Protocol Communication
It is recommended to bookmark this series and follow the tutorials step by step. All code will besynced updated to the official Gitee repository.
In embedded IoT applications, a device can not only act as a TCP Client to actively connect to a server, but also as a TCP Server to listen on a local port, waiting for computers, host computers, or other network devices to actively connect.
TCP Server is a server-side program based on the TCP protocol. It binds to the local IP address and port number, and continuously listens for connection requests from TCP Clients. After a client successfully connects, the server can establish a reliable TCP connection with the client and perform bidirectional data communication.
1.1 What is TCP Server
TCP Server can be understood as "the party waiting for a connection."
Its main function is to listen for client connection requests on a specified port. Once a TCP Client connects, the Server can establish a connection with that client and perform data sending and receiving through this connection.
In simple terms:
TCP Server: Starts first, waits for client connections TCP Client: Actively connects to TCP Server
1.2 Relationship Between TCP Server and TCP Client
TCP communication typically consists of two roles: Server and Client.
Role
Description
TCP Server
Binds local IP and port, listens for client connections
TCP Client
Actively connects to the TCP Server's IP and port
After connection established
Both parties can send and receive data
1.3 TCP Server Workflow
The communication process of TCP Server is shown in the following diagram:
From the flow, it can be seen that the core of TCP Server is: creating a Socket, binding IP and port, listening for client connections, and performing data sending and receiving after the connection is successful.
1.4 Advantages of TCP Server
The main advantages of TCP Server are as follows:
Advantage
Description
Reliable connection
Based on TCP protocol, suitable for stable data transmission
Bidirectional communication support
After the connection is established, both Server and Client can send and receive data
Suitable for host computer access
Computers, gateways, or other clients can actively connect to the device
Convenient for local debugging
Communication can be quickly verified using tools like SocketTester
Suitable for device control
Can be used for parameter configuration, status querying, remote control, and other scenarios
For embedded devices, TCP Server is commonly used in scenarios where "the device waits for the host computer to connect." For example, after powering on, the device listens on a fixed port, and the host computer actively connects to the device to read device status, send control commands, or perform parameter configuration.
Used as TCP Client on the computer to connect to the development board
2.2 Hardware Preparation
As shown in the figure, the physical image of the W55RP20-EVB-MKR development board.
The following hardware needs to be prepared:
W55RP20-EVB-MKR development board × 1
USB data cable (must support data transmission, pure charging cables cannot be used) × 1
Standard Ethernet cable × 1
Router or switch × 1
W55RP20-EVB-MKR has an onboard Ethernet interface, no additional soldering or wiring of other components is needed, it is plug-and-play.This greatly reduces the probability of wiring errors and hardware failures.
W55RP20 is fully compatible with the Raspberry Pi Pico UF2 firmware flashing method, which is simple to operate and does not require an additional programmer:
Press and hold the BOOTSEL button on the W55RP20-EVB-MKR development board
Connect the development board to the computer using a Micro USB data cable
After the computer recognizes a USB drive named RPI-RP2, release the BOOTSEL button
Drag and drop the downloaded W55RP20_firmware.uf2 firmware file into the USB drive
The development board will automatically restart, and the firmware flashing is complete
Note: If the computer does not recognize the RPI-RP2 USB drive, please try replacing the USB data cable, re-plugging the development board, or changing the computer's USB port.
4. Hardware Connection and Development Environment Configuration
4.1 Hardware Connection
The connection of W55RP20-EVB-MKR is very simple, requiring only two steps:
Connect the development board to the computer using a USB data cable, for power supply, code flashing, and serial debugging
Connect the Ethernet interface of the development board to the LAN port of the router using an Ethernet cable
As shown in the figure, the hardware connection schematic diagram
4.2 Thonny Development Environment Configuration
Open Thonny software, click the top menu bar "Run" → "Configure Interpreter"
Switch to the "Interpreter" tab
Select MicroPython (generic) from the "Interpreter" dropdown list
Select the serial port corresponding to W55RP20-EVB-MKR from the "Port" dropdown list (usually displayed as Board CDC @ COMx)
Check "Restart interpreter before running code" and "Synchronize device's real-time clock"
Click "OK" to complete the configuration
If the development board does not appear in the port list, please try:
Re-plug the USB data cable
Replace with a USB data cable that supports data transmission
Close other software occupying the serial port (such as Serial Assistant, Arduino IDE, etc.)
Re-flash the MicroPython firmware
5. SocketTester Configuration
In this experiment, the development board acts as a TCP Server, and the computer's SocketTester acts as a TCP Client.
After opening SocketTester, configure it as follows:
Parameter
Setting
Protocol
TCP client
Server IP address
192.168.1.123
Server port number
8087
Decode as
ASCII
Encode as
ASCII
After configuration is complete, click Connect, and the computer will actively connect to the development board's TCP Server.
Note: Server IP address needs to be filled with the IP address printed by the development board in Thonny.In this experiment, the development board IP is 192.168.1.123, and the listening port is 8087.
The SocketTester configuration interface is shown in the following figure:
6. TCP Server Example Code
6.1 Complete Code
Open the TCP Server example file, or enter the following code in Thonny:
fromwiznet_initimportwiznet importusocketassocket importtime # Initialize W55RP20-EVB-MKR network # dhcp=True means automatically obtaining IP address through the router nic = wiznet("W55RP20-EVB-MKR", dhcp=True) # Get the development board's current IP address local_ip = nic.ifconfig()[0] # Set TCP Server listening port local_port = 8087 print("==================================") print(" TCP Server started successfully ✅") print(" IP:", local_ip) print(" Port:", local_port) print("==================================") # Create TCP Socket # AF_INET indicates using IPv4 # SOCK_STREAM indicates using TCP protocol s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the development board's actual IP address and listening port # The computer's TCP Client needs to connect to this IP and port s.bind((local_ip, local_port)) # Start listening for client connections # Parameter 1 means a maximum of 1 client can queue waiting for connection s.listen(1) print("Waiting for computer TCP Client to connect...") # Block and wait for the computer's TCP Client to connect # After successful connection, conn is used for subsequent data sending/receiving, addr is the client address information conn, addr = s.accept() print("✅ Computer connected:", addr) # Continuously receive data sent from the computer whileTrue: try: # Receive data sent from the computer, maximum 1024 bytes data = conn.recv(1024) # If no data is received, the computer may have disconnected ifnotdata: print("Computer actively disconnected") break # Print the received data print("Received:", data) # Compose reply data reply = b"TCP Server : "+data # Send reply data to the computer's TCP Client conn.send(reply) exceptExceptionase: # If an exception occurs during communication, print exception information and exit the loop print("Connection exception:", repr(e)) break # Close client connection conn.close() # Close TCP Server Socket s.close() print("❌ Connection disconnected")
6.2 Key Function Description
The core functions of TCP Server in this example are as follows:
Function/Statement
Purpose
s.bind((local_ip, local_port))
Bind the development board's IP and listening port
s.listen(1)
Start listening for TCP Client connections
conn, addr = s.accept()
Wait for client connection
conn.recv(1024)
Receive data sent by the client
conn.send(reply)
Send reply data to the client
Among them, accept() will block and wait for the computer to connect, and recv() will block and wait for the computer to send data.
7. Running Results and Communication Verification
After completing the SocketTester configuration and running the TCP Server example program, you can observe the communication results through the Thonny Shell and SocketTester window.
7.1 Thonny Serial Output Results
After running the program, the Thonny Shell outputs the following:
>>> %Run -c $EDITOR_CONTENT MPY: soft reboot Waiting for the network to connect... Waiting for the network to connect... Waiting for the network to connect... Waiting for the network to connect... MAC Address: 02:90:86:88:4d:56 IP Address: ('192.168.1.123', '255.255.255.0', '192.168.1.1', '202.96.134.33') ================================== TCP Server started successfully ✅ IP: 192.168.1.123 Port: 8087 ================================== Waiting for computer TCP Client to connect... ✅ Computer connected: ('192.168.1.119', 53891) Received: b'hello' Received: b'123'
From the running results, it can be seen that the development board obtained the IP address 192.168.1.123 via DHCP, and started TCP Server on port 8087.
The computer's SocketTester as TCP Client successfully connected to the development board, with the connection address:
('192.168.1.119', 53891)
Subsequently, the computer sent hello and 123, and the development board received b'hello' and b'123' respectively, indicating that TCP Server data reception was successful.
7.2 SocketTester Reception Results
In the SocketTester send box on the computer, enter:
hello
Or:
123
After clicking Send, the development board will receive this data and send back:
TCP Server : hello TCP Server : 123
The SocketTester reception window shows:
TCP Server : hello TCP Server : 123
The actual running effect is shown in the following figure, with the Thonny running log on the left and the SocketTester TCP Client data send/receive window on the right.
From the screenshot, it can be seen that the computer's SocketTester has successfully connected to the development board's TCP Server, and received the development board's echo TCP Server : hello and TCP Server : 123, indicating that bidirectional communication verification was successful.
7.3 TCP Server Communication Video Demonstration
The following video demonstrates the process of W55RP20-EVB-MKR acting as a TCP Server, waiting for the computer's TCP Client to connect, and completing data echo.
8. Common Issues One-Stop Troubleshooting Guide
8.1 Computer TCP Client Connection Failed
Problem Phenomenon
Troubleshooting Steps
SocketTester prompts unable to connect
1. Confirm that the development board program is already running2. Confirm that Thonny has printed Waiting for computer TCP Client to connect...3. Confirm that SocketTester has selected TCP client4. Confirm that Server IP is filled with the development board's IP5. Confirm that the port number is 8087
8.2 Incorrect Server IP or Port
Problem Phenomenon
Troubleshooting Steps
Connection failed after clicking Connect
1. Check the actual IP address of the development board in Thonny2. Confirm that Server IP address in SocketTester matches the development board's IP3. Confirm that Server port number matches local_port in the code4. Confirm that the computer and development board are on the same local network
The development board listening port in this article's code is:
local_port = 8087
If your development board's IP has changed, you need to update it in SocketTester accordingly.
8.3 Port Occupied or Not Released
If you frequently stop and rerun the TCP Server program, you may encounter issues with the port not being released or abnormal connection states.
You can try:
Close SocketTester and reopen it
Stop the program in Thonny and rerun it
Re-plug the development board's USB
Change the listening port, for example from 8087 to 8088
Confirm that no other program is connecting to the same port
8.4 Program Stuck at accept()
The following in the code:
conn, addr = s.accept()
is a blocking wait for the computer's TCP Client to connect.
If the computer has not clicked Connect, the program will stay here indefinitely. This is normal behavior and is not a crash.
Solutions:
Open SocketTester
Select TCP client
Enter the development board's IP and port
Click Connect
Check if Thonny prints ✅ Computer connected
8.5 Computer Cannot Receive Reply
If the development board has received data but the computer's SocketTester does not show a reply, you can check:
Whether SocketTester has checked Don't log data
Whether the SocketTester reception area has been cleared
Whether Decode as is set to ASCII
Whether the development board code has executed conn.send(reply)
Whether the TCP connection has already been disconnected
When the computer normally receives a reply, it should display:
TCP Server : hello
TCP Server : 123
9. W55RP20 Core Advantages Comparison
To give you a more intuitive understanding of the value of W55RP20, we compared the three mainstream embedded Ethernet solutions:
Comparison Dimension
W55RP20 Integrated Solution
External PHY Chip Solution
External Serial-to-Ethernet Module Solution
BOM Cost
Low(Single chip)
Medium-High(MCU + Module + Peripheral components)
High
PCB Area
Small(Only Ethernet port circuitry needed)
Large(Need to reserve chip and routing space)
High
Development Difficulty
Low(One line of code for networking)
Medium-High(Debug protocol stack, write drivers)
Low
Network Stability
Extremely High(WIZnet has focused on hardware TCP/IP protocol stack for 25 years)
Variable(Requires high expertise from R&D personnel, familiarity with protocol stack and network development to debug stably)
Variable(Depends on R&D company's capability level)
CPU Resource Usage
0%(Protocol stack network processing entirely handled by hardware)
Over 50%(Protocol stack runs entirely on MCU, occupying related resources)
0%
Hardware Socket Count
8 independent hardware Sockets
Depends on MCU capability, theoretically supports multiple channel expansion
Generally single-channel transparent transmission
Network Throughput
Up to 15Mbps
Depends on MCU capability
Approximately 3-5Mbps
Interface Ease of Use
Single chip integration
MCU needs MII/RMII interfaces
TTL interface
Deployment Difficulty
Low(Mature MicroPython firmware, most application layer protocols have library files, can be flexibly added and deployed)
High(Application layer protocols require manual porting of open-source libraries for adaptation)
Depends on module integration, unimplemented features require self-encapsulation and parsing
10. Typical Application Scenarios
The W55RP20 chip integrates Ethernet functionality and, combined with its industrial-grade stability, is very suitable for the following application scenarios:
Industrial Data Acquisition Gateway: Simplify on-site deployment, achieve stable uploading of sensor data
Remote Monitoring Terminal: Used for remote monitoring of equipment status in factories, server rooms, substations, and other environments
Serial-to-Ethernet Device: Quickly upgrade traditional RS232/RS485 serial devices to Ethernet devices
Smart Building Node: Used for network control of lighting, HVAC, access control, and other building equipment
Industrial PLC Expansion Module: Add Ethernet communication capability to PLCs, enabling remote programming and data acquisition
Article Summary
Starting from the basic concepts of TCP Server, this article systematically introduced how to implement TCP Server communication based on the W55RP20-EVB-MKR development board. With the support of the WIZnet hardware TCP/IP protocol stack and MicroPython's socket interface, only a small amount of code is needed to complete the entire process of the development board listening on a port, waiting for client connections, and performing bidirectional data communication, laying a solid foundation for advanced applications such as UDP communication, HTTP applications, and MQTT cloud connectivity.
Reviewing the core points of this article:
TCP Server Basic Concepts: Understood the core role of TCP Server as "the party waiting for a connection" — binding the local IP and port, continuously listening for client connection requests, and performing bidirectional data communication with the Client after a successful connection
SocketTester Configuration: Completed the configuration of the TCP Client testing tool on the computer, including protocol selection (TCP client), Server IP address (development board IP), and Server port number (development board listening port) settings, ensuring consistency with the development board code parameters
TCP Server Code Implementation: Used socket.socket() to create a Socket, bind() to bind IP and port, listen() to start listening, accept() to block and wait for client connections, and recv() to receive data, send() to send replies
Communication Result Verification: Verified bidirectionally through Thonny serial output and SocketTester reception window, confirming that the development board successfully received data from the computer and echoed TCP Server : hello, TCP Server communication function is complete
Fault Troubleshooting: Summarized troubleshooting methods for five categories of common issues: computer TCP Client connection failure, incorrect IP/port, port occupied or not released, program stuck at accept(), and computer unable to receive reply
W55RP20 Solution Advantages: Compared the W55RP20 integrated solution, external PHY chip solution, and external serial-to-Ethernet module solution; W55RP20's single-chip integration, 0% CPU usage, and hardware Sockets are particularly advantageous in device listening and host computer active connection scenarios
After mastering the TCP Server communication technology in this article, your embedded device already has the core capability to listen on a port, wait for client connections, and perform bidirectional data interaction. The next article will move on to learning UDP Unicast Data Communication, understanding the characteristics and applicable scenarios of connectionless communication.
11. Series Preview and Resource Access
11.1 Series Preview
The next tutorial will cover UDP Unicast Data Communication in W55RP20 MicroPython development.
Unlike TCP, UDP does not require establishing a connection, making it suitable for communication scenarios with high real-time requirements that can tolerate minor packet loss.