pdf-icon

UIFlow Guide

UIFlow 1.0 Project

Socket

UDP Server

案例程序

创建UDP Server监听数据接收, 并发送返回相同的数据内容。通过网络相关的API可获取当前本机的IP地址, 用于提供其他Client数据发送。

from m5stack import *
from m5ui import *
from uiflow import *
import network
import socket

setScreenColor(0x222222)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('SSID', 'PASSWORD')
print(wlan.ifconfig())

udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpsocket.bind(('0.0.0.0', 5000))
while True:
  print(udpsocket.recv(1024))
  wait_ms(2)

功能说明

udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpsocket.bind(('0.0.0.0', 5000))
  • 创建socket server并指定监听的IP(通常使用0.0.0.0监听本机)和端口
udpsocket.sendto('Hello', ('192.168.31.11', 5000))
  • 发送数据到指定IP和端口
udpsocket.close()
  • 关闭socket
data = udpsocket.recv(1024)
  • 阻塞接收监听数据, 并设置最大buffer长度, 接收到数据时返回。
data = udpsocket.read(10)
  • 阻塞接收监听数据, 并设置接收buffer长度,当接收buffer填满时返回。

UDP Client

案例程序

创建UDP Client发送数据到指定服务器。

from m5stack import *
from m5ui import *
from uiflow import *
import socket
import time
setScreenColor(0x222222)

udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpsocket.connect(('192.168.31.10', 5000))
while True:
  udpsocket.send('Hello World')
  wait(1)
  wait_ms(2)

功能说明

udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpsocket.connect(('192.168.31.10', 5000))
  • 创建socket server并指定发送数据目标IP和端口
udpsocket.send('Hello World')
  • 发送字符数据
udpsocket.write('')
  • 写入原始数据
udpsocket.sendto('Hello World', ('192.168.31.10', 5000))
  • 发送数据至指定IP和端口
udpsocket.close()
  • 关闭socket
data = udpsocket.recv(1024)
  • 阻塞接收监听数据, 并设置最大buffer长度, 接收到数据时返回。
data = udpsocket.read(10)
  • 阻塞接收监听数据, 并设置接收buffer长度,当接收buffer填满时返回。
On This Page