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)

效果:

相关推荐
Cx330❀10 小时前
【Linux网络】网络层协议 IP :从网络层原理到 Linux 内核源码
linux·运维·服务器·网络·tcp/ip·ai·ai编程
FPC工厂——皇榜科技11 小时前
机器人灵巧手线路板:从“握得住”到“摸得准”:一只机械手的柔性神经密码
网络·人工智能·科技·机器人·pcb工艺
Orange_sparkle12 小时前
Pi Agent vs LangGraph:从人机交互、企业 RAG 到持久化工作流的完整选型指南
java·网络·人机交互
xiaoye-duck13 小时前
《Linux 网络编程》深入传输层 UDP 协议原理:端口、报文、缓冲区与内核源码解析
linux·网络·udp
好评12413 小时前
【Linux】数据链路层
linux·运维·网络
天衍四九-13 小时前
第一章:从 LLM 到 Agent —— DeepSeek Harness 入门
网络·数据库·人工智能·python
Jae den13 小时前
网络丢包是什么?
网络
XR12345678815 小时前
医院无线整网高密覆盖选型深度解析
运维·网络
发量惊人的中年网工15 小时前
企业一体化安全网关选型:适用规模、需求架构与实施建议
网络
取啥都被占用15 小时前
两个网络供应商靠树莓派跨个域
网络·树莓派