UDP-Server Example Explanation#
Environment Preparation#
To ensure the smooth demonstration of UDP communication, we need to confirm that the following environment is properly configured:
Hardware Connection#
Please ensure your CanMV development board and computer are connected to the same router or switch via network cables, forming a local area network.
Ensure that the router or switch is working properly to guarantee the stability of the network connection.
Disable Firewall#
To prevent the firewall from blocking UDP communication, it is recommended to temporarily turn off the computer’s firewall.
Tool Preparation#
Download and install NetAssist Network Debugging Assistant as a network communication testing tool to help achieve the sending and receiving of network data.
Obtain IP Address#
Open the command prompt (CMD), enter
ipconfig, query and record the IP address of the computer’s network card for subsequent configuration and testing use.
Server Routine Analysis#
This routine demonstrates how to create a simple UDP server, including configuring network interfaces, creating sockets, binding addresses and ports, receiving and sending data, and closing sockets. Through this routine, you can learn how to build basic network communication applications.
Import Necessary Libraries#
import socket
import network
import time
socket: Used to create sockets, which is the foundation of network communication.network: Used to configure network interfaces, such as LAN or WLAN.time: Used for delay processing, which may be used for timeout control in network requests.
Configure Network Interface#
def network_use_wlan(is_wlan=True):
if is_wlan:
sta = network.WLAN(0)
sta.connect("TEST", "12345678")
print(sta.status())
while sta.ifconfig()[0] == '0.0.0.0':
os.exitpoint()
print(sta.ifconfig())
ip = sta.ifconfig()[0]
return ip
else:
a = network.LAN()
if not a.active():
raise RuntimeError("LAN interface is not active.")
a.ifconfig("dhcp")
print(a.ifconfig())
ip = a.ifconfig()[0]
return ip
This code configures the network interface based on input parameters, with the following flow:
WLAN Mode:
If
is_wlan=True, configures the wireless network interface (WLAN) and connects to the specified Wi-Fi network (SSID is “TEST”, password is “12345678”).Outputs the WLAN connection status and waits for a valid IP address to be assigned.
After a successful connection, prints the network configuration and returns the IP address.
LAN Mode:
If
is_wlan=False, configures the wired network interface (LAN).Activates the LAN interface and checks the status. Raises an exception if not activated.
Uses DHCP to obtain an IP address, prints the network configuration, and returns the IP.
Create UDP Socket#
# Create UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set socket options, allow address reuse
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Get address and port number and bind the socket
ai = socket.getaddrinfo(ip, 8080)
addr = ai[0][-1]
s.bind(addr)
We created a UDP-type socket and set the SO_REUSEADDR option to allow address reuse. Then, we obtained the address and port number information through getaddrinfo, and bound the socket to that address and port.
Receive and Send Data#
# Delay 1 second to ensure the socket binding is complete
time.sleep(1)
# Receive data and reply
for j in range(10):
try:
data, addr = s.recvfrom(800) # Receive data, up to 800 bytes
print("Received:", data, "from", addr)
# Reply with a message containing the received data and receive count
response = b"%s have recv count=%d " % (data, j)
s.sendto(response, addr)
except Exception as e:
print("Error:", e) # Print exception information for debugging
# Close the socket
s.close()
print("UDP Server exited!!")
The program receives up to 800 bytes of data through the recvfrom method and prints the received data along with the client address. Subsequently, it constructs a reply message and sends it through sendto. The program includes exception handling to capture and debug errors.
Complete Routine#
# Configure tcp/udp socket debugging tool
import socket
import time, os
import network
def network_use_wlan(is_wlan=True):
if is_wlan:
sta = network.WLAN(0)
sta.connect("TEST", "12345678")
print(sta.status())
while sta.ifconfig()[0] == '0.0.0.0':
os.exitpoint()
print(sta.ifconfig())
ip = sta.ifconfig()[0]
return ip
else:
a = network.LAN()
if not a.active():
raise RuntimeError("LAN interface is not active.")
a.ifconfig("dhcp")
print(a.ifconfig())
ip = a.ifconfig()[0]
return ip
def udpserver():
# Get the LAN interface IP address
ip = network_use_wlan(True)
# Get the address corresponding to the address and port number
ai = socket.getaddrinfo(ip, 8080)
print("Address infos:", ai)
addr = ai[0][-1]
print("udp server %s port:%d\n" % (ip, 8080))
# Establish a socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
time.sleep(1) # Delay 1 second to ensure the socket is ready
counter = 0
while True:
os.exitpoint()
data, addr = s.recvfrom(800)
if data == b"":
continue
print("recv %d" % counter, data, addr)
s.sendto(b"%s have recv count=%d " % (data, counter), addr)
counter += 1
if counter > 10:
break
s.close()
print("udp server exit!!")
#main()
udpserver()
For specific interface definitions, please refer to socket and network.
Example Phenomena and Operation Instructions#
After running the code, the serial terminal will output the server’s IP address and port number information:

Select UDP in the network debugging assistant and configure the connection parameters:
Send data and observe the server’s response:
