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)

效果:

相关推荐
G_H_S_3_4 小时前
【网络运维】Linux:LNMP 项目实践
linux·运维·服务器·网络
Fanmeang7 小时前
MPLS LDP概述
运维·网络·华为·路由·mpls·标签·ldp
千码君20168 小时前
计算机网络:超网即路由聚合一定需要连续的IP地址吗?
网络协议·tcp/ip·计算机网络·子网掩码·路由聚合·超网·网络前缀
Menior_8 小时前
【网络基础】深入理解 TCP/IP 协议体系
网络·网络协议·tcp/ip
稚辉君.MCA_P8_Java9 小时前
常见通信协议详解:TCP、UDP、HTTP/HTTPS、WebSocket 与 GRPC
服务器·tcp/ip·http·https·udp
张飞的猪大数据9 小时前
通过Certbot自动申请更新HTTPS网站的SSL证书
网络协议·https·ssl
小明的小名叫小明11 小时前
区块链技术原理(5)-网络
网络·区块链
NorthCastle12 小时前
Docker 网络-单机版
网络·docker·docker网络基础概念·docker网络基础命令
sniper_fandc13 小时前
VirtualBox虚拟机网卡配置
linux·网络·虚拟机
未名编程13 小时前
【已解决】报错:WARNING: pip is configured with locations that require TLS/SSL
网络协议·ssl·pip