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)

效果:

相关推荐
我科绝伦(Huanhuan Zhou)1 小时前
Systemctl 与 Systemd 全面指南:Linux 系统服务管理详解
linux·服务器·网络
world-wide-wait1 小时前
python高级05——HTTP协议和静态服务器
网络·网络协议·http
止水编程 water_proof1 小时前
Java--网络编程(二)
java·开发语言·网络
Ankie Wan2 小时前
ARP: Address Resolution Protocol (ARP),IP转mac address
网络协议·tcp/ip·rfc·arp
沐浴露z2 小时前
【深入理解计算机网络10】UDP协议详解
网络·网络协议·计算机网络·udp
world-wide-wait3 小时前
python高级04——网络编程
linux·服务器·网络
特种加菲猫3 小时前
网络协议分层:解密TCP/IP五层模型
linux·网络·笔记
conkl4 小时前
Linux IP 网络配置与管理详解
linux·网络·tcp/ip
Yana.nice5 小时前
sshd -t与-T的区别
网络
asdfg12589635 小时前
SAN和NAS的区别
网络