代码:
import network
import socket
import timedef wifiInit(name, port):ap = network.WLAN(network.AP_IF) # 创建一个热点ap.config(essid=name, authmode=network.AUTH_OPEN) # 无需密码ap.active(True) # 激活热点ip = ap.ifconfig()[0] # 获取ip地址print("wifi ip:", ip)udpSocket = Nonetry:while True:if not ap.isconnected(): # 等待client连接print("no client")time.sleep(1)else:print("client connected")if udpSocket is None:udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 创建UDP套接字udpSocket.bind((ip, port)) # 绑定地址和端口号print('UDP socket created')print("waiting for data")data, addr = udpSocket.recvfrom(1024) # 接收数据(1024字节大小)print("received data:", data.decode())# 模拟回复数据给客户端response = "Received data: " + data.decode()udpSocket.sendto(response.encode(), addr)if data.decode() == "#end":print("client socket disconnected")udpSocket.close()udpSocket = Noneap.disconnect()ap.active(False)print("wifi ap disconnected")breakif not ap.isconnected():udpSocket.close()udpSocket = Noneprint("client disconnected")breakexcept Exception as e:print(f"出现异常: {e}")finally:if udpSocket:udpSocket.close()print("Socket closed")wifiInit("wifi32", 66)
效果: