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)

效果:

相关推荐
谷粒.19 分钟前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
北京耐用通信6 小时前
电磁阀通讯频频“掉链”?耐达讯自动化Ethernet/IP转DeviceNet救场全行业!
人工智能·物联网·网络协议·安全·自动化·信息与通信
斯南6 小时前
wireshark的基本使用,过滤请求,过滤数据,追踪数据
网络·测试工具·wireshark
yenggd7 小时前
首次eve-ng锐捷设备园区网案例实现
网络·智能路由器
2301_810746319 小时前
CKA冲刺40天笔记 - day20-day21 SSL/TLS详解
运维·笔记·网络协议·kubernetes·ssl
面向星辰10 小时前
桌面运维岗 day02 计算机硬件_内存条
网络
Cher ~10 小时前
OSI 七层模型
网络·智能路由器
克喵的水银蛇10 小时前
Flutter 网络请求实战:Dio 封装 + 拦截器 + 数据解析
网络·flutter
汤愈韬10 小时前
知识点3:动态目的NAT的配置总结
网络·网络协议·网络安全·security·huawei
00后程序员张11 小时前
HTTPS Everywhere 时代的抓包挑战,从加密流量解析到底层数据流捕获的全流程方案
网络协议·http·ios·小程序·https·uni-app·iphone