UDP-Client Routine Explanation#
Environment Preparation#
To ensure the smooth progress of the UDP communication demonstration, we need to confirm that the following environment is properly configured:
Hardware Connection#
Please ensure that your CanMV development board and computer are connected to the same router or switch via Ethernet cable to form a LAN.
Ensure that the router or switch is working properly to guarantee stable network connectivity.
Disable Firewall#
To prevent the firewall from blocking UDP communication, it is recommended to temporarily disable the computer’s firewall.
Tools Preparation#
Download and install NetAssist Network Debugging Assistant as a network communication testing tool to help send and receive network data.
Obtain IP Address#
Open the Command Prompt (CMD), enter
ipconfig, query and record the IP address of the computer’s network adapter for subsequent configuration and testing.
Client Routine Analysis#
This UDP client routine demonstrates how to create a simple UDP client, including connecting to a server, sending data, and closing the connection. You can learn the basic methods for building UDP communication applications through this routine.
Importing Necessary Libraries#
import socket
import network
import time
The
socketlibrary is responsible for creating network communication sockets.The
networklibrary is used to configure network interfaces, such as enabling LAN or WLAN.The
timelibrary provides delay operations, typically used to control data sending frequency or handle timeouts.
Configuring the 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 function configures the network interface based on whether a wireless network (WLAN) or wired network (LAN) is selected. The specific steps are as follows:
WLAN Mode: Attempt to connect to the Wi-Fi network, wait until a valid IP address is obtained, and then return it.
LAN Mode: Activate the LAN interface and use DHCP mode to obtain an IP address.
Creating a UDP Socket#
# 获取服务器的 IP 和端口号
ai = socket.getaddrinfo('172.16.1.174', 8080)
print("Address infos:", ai)
addr = ai[0][-1] # 提取 IP 和端口号
print("Connecting to address:", addr)
# 创建 UDP 套接字
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Here, socket.getaddrinfo is used to obtain the server’s IP and port information, and the address and port number are extracted. Then a UDP socket is created.
Sending Data#
# 发送测试消息
for i in range(10):
message = "K230 UDP client send test {0} \r\n".format(i)
print("Sending:", message)
# 将消息编码成字节并发送
bytes_sent = s.sendto(message.encode(), addr)
print("Bytes sent:", bytes_sent)
# 暂停一段时间以等待下次发送
time.sleep(0.2)
In the loop, the program generates a test message and sends it to the specified server address via the sendto function. The message needs to be converted into a byte string before sending. After successful sending, the number of bytes sent is printed, and a small delay is set.
Closing the Socket#
# 关闭套接字
s.close()
print("Client ended.")
After data sending is complete, the socket is closed to release resources.
Complete Routine#
import socket
import os
import time
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 udpclient():
# 配置网络接口
network_use_wlan(True)
# 获取服务器地址和端口号
ai = socket.getaddrinfo('192.168.1.110', 8080)
print("Address infos:", ai)
addr = ai[0][-1]
print("Connect address:", addr)
# 创建 UDP 套接字
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in range(10):
message = "K230 UDP client send test {0} \r\n".format(i)
print("Sending:", message)
# 发送字符串
bytes_sent = s.sendto(message.encode(), addr)
print("Bytes sent:", bytes_sent)
time.sleep(0.2)
# 关闭套接字
s.close()
print("Client ended.")
# 启动客户端
udpclient()
Run and Test#
Use NetAssist Network Debugging Assistant to establish a UDP connection:
Modify the server IP address in the code:
ai = socket.getaddrinfo("172.16.1.174", 8080)
After running the example, NetAssist will display the received UDP data packet:
