ESP32实现UDP连接——micropython版本

代码:

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)

效果:
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值