ESP32实现UDP连接——micropython版本

代码:

bash 复制代码
import network
import socket
import time

def 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 = None

    try:
        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 = None
                    ap.disconnect()
                    ap.active(False)
                    print("wifi ap disconnected")
                    break
                if not ap.isconnected():
                    udpSocket.close()
                    udpSocket = None
                    print("client disconnected")
                    break

    except Exception as e:
        print(f"出现异常: {e}")
    finally:
        if udpSocket:
            udpSocket.close()
            print("Socket closed")

wifiInit("wifi32", 66)

效果:

相关推荐
GDAL13 小时前
Nginx TCP/UDP四层转发(Stream模块)完整深入教程
tcp/ip·nginx·udp
2401_8653825016 小时前
密评与等保的关系:不是替代,而是互补
网络·信息化造价
白狐_79818 小时前
408计算机网络第3章:PPP协议——帧格式、LCP/NCP、状态机与真题精讲
网络·计算机网络·智能路由器
MIXLLRED18 小时前
解决——Ubuntu远程桌面指令更换网络
linux·网络·ubuntu
zt1985q20 小时前
本地部署开源网络书签与内容管理工具 Karakeep 并实现外部访问
运维·服务器·网络·数据库·网络协议·开源
白狐_7981 天前
408计算机网络第3章:以太网交换机与共享式以太网——知识总结
服务器·网络·计算机网络
笨鸟先飞,勤能补拙1 天前
网络安全等级保护 2.0:从定级备案、建设整改到持续合规的系统指南
网络·人工智能·windows·安全·web安全·网络安全·github
wgh6531 天前
策略路由实验
网络
難釋懷1 天前
Nginx日志
前端·网络·nginx
Loongproxy1 天前
大规模采集为啥用隧道代理IP?会话保持如何做到无感轮换
java·服务器·网络