【ESP32+Python】连接WebSocket服务例子

import ujson
import usocket
import ubinascii

# 配置WebSocket地址和端口
SERVER = ""#域名 根据实际情况可能需要修改
PORT = 80  #端口 根据实际情况可能需要修改
PATH = ""#域名后路径 根据实际情况可能需要修改

# 函数:创建WebSocket连接
def create_connection():
    addr_info = usocket.getaddrinfo(SERVER, PORT)[0]
    s = usocket.socket(addr_info[0], usocket.SOCK_STREAM)
    s.connect(addr_info[-1])
    s.send(b"GET " + PATH + " HTTP/1.1\r\nHost: " + SERVER + b"\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\nSec-WebSocket-Version: 13\r\n\r\n")
    return s

# 函数:发送数据
def send_data(socket, data):
    # 将数据转换为JSON字符串
    json_data = ujson.dumps(data)
    # 构建WebSocket帧来发送数据
    socket.send(b"\x81" + ubinascii.unhexlify('%02x' % len(json_data)) + json_data.encode())

# 函数:接收数据
def receive_data(socket):
    # 读取响应
    response = socket.recv(512)
    # 找到JSON数据的开始位置
    start = response.find(b'\x81')
    if start != -1:
        # 提取有效载荷长度
        length = response[start+1] & 127
        # 根据长度提取JSON字符串,跳过2字节的基础帧头部,加上长度得到JSON数据的起点
        json_start = start + 2
        json_data = response[json_start:json_start+length]
        # 打印JSON字符串
        print("Received:", json_data.decode())
    else:
        print("No JSON data found")

# 主函数
def start_websocket():
    try:
        # 创建WebSocket连接
        ws = create_connection()
        # 发送数据
        send_data(ws, {"name": "我是设备"})
        # 接收并打印响应
        receive_data(ws)
    finally:
        # 关闭连接
        ws.close()

你可能感兴趣的:(ESP32+Python,python,websocket,开发语言)