Skip to main content

A WebSocket server library for MicroPython on ESP32

Project description

micropython-websocket_server

适用于ESP32的MicroPython WebSocket-server模块。

安装方法

在Thonny中安装到ESP32:

  1. 用USB将ESP32连接到电脑
  2. 打开Thonny,右下角切换为 MicroPython(ESP32)
  3. 菜单 Tools → Manage packages
  4. 搜索 micropython-websocket_server
  5. 点击安装

使用示例

import network
import micropython_websocket_server as websocket_server

def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print("连接 Wi-Fi...")
        wlan.connect("你的WiFi名称", "你的WiFi密码")
        while not wlan.isconnected():
            pass
    ip = wlan.ifconfig()[0]
    print("Wi-Fi 已连接,ESP32 IP 地址:", ip)
    print("请在 PC 端连接: ws://{}:8765".format(ip))
    return ip

do_connect()

# 创建并启动服务器
server = websocket_server.WebSocketServer("0.0.0.0", 8765)
server.start()
print("WebSocket 服务器已启动,等待连接...")

try:
    while True:
        # 阻塞等待一个客户端连接
        conn, addr = server.accept()
        if conn is None:
            continue   # 握手失败,继续等待

        print("客户端已连接:", addr)

        # 与该客户端通信直到断开
        try:
            while True:
                msg = conn.recv()         # 阻塞接收
                print("收到:", msg)
                conn.send(msg)            # 原样返回
        except websocket_server.WebSocketConnectionClosedException:
            print("客户端已断开:", addr)
        finally:
            conn.close()
            server.remove_client(conn)

finally:
    server.stop()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

micropython_websocket_server-0.1.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

micropython_websocket_server-0.1.0-py3-none-any.whl (11.4 kB view details)

Uploaded Python 3

File details

Details for the file micropython_websocket_server-0.1.0.tar.gz.

File metadata

File hashes

Hashes for micropython_websocket_server-0.1.0.tar.gz
Algorithm Hash digest
SHA256 103afa189efa4e99fa230880506615e2978858012e2634e738e53cb1e990aae2
MD5 cec9bc250592917be23b1f27866e3077
BLAKE2b-256 72e7caced98638d4a3841f3f253fc40d22c14d8e009caf4b84bb4439534125ff

See more details on using hashes here.

File details

Details for the file micropython_websocket_server-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for micropython_websocket_server-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dd6982c9a21135e177ce10ecb8d26f319ca41428333b38243c01778ed7e93ffc
MD5 dae141518c8b9481e92056e23a12475b
BLAKE2b-256 0709164090125f7e70a8af617232b069bbef6f797620599d4515765b7d074b87

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page