Note

This is the documentation for the latest development branch and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

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.

example/images/network/image-20240722145319713.png

Tools Preparation#

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.

example/images/network/image-20240722145500693.png

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 socket library is responsible for creating network communication sockets.

  • The network library is used to configure network interfaces, such as enabling LAN or WLAN.

  • The time library 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:

  1. WLAN Mode: Attempt to connect to the Wi-Fi network, wait until a valid IP address is obtained, and then return it.

  2. 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#

  1. Use NetAssist Network Debugging Assistant to establish a UDP connection:

example/images/network/image-20240722171950467.png
  1. Modify the server IP address in the code:

ai = socket.getaddrinfo("172.16.1.174", 8080)
  1. After running the example, NetAssist will display the received UDP data packet:

example/images/network/image-20240722172037608.png
Comments list
Comments
Log in