ESP32向阿里云传递数据入门

文章介绍了如何在服务器上安装Python并使用socket库创建TCP服务器,同时展示了ESP32通过WiFi连接到服务器进行通信的过程,包括Linux系统管理、端口开放和安全组配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器安装python

重置linux密码

开放端口

sudo ufw status #查看ufw状态
 
sudo ufw enable #开启ufw
 
sudo ufw allow 8000 #开启8000端口,换成自己的

配置安全组:安全组>管理规则>手动添加

服务器端python代码:

from socket import *
from time import ctime
import time
# 作为tcp服务端

addr = ("172.24.80.147", 8000)

tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(addr)
tcpServerSocket.listen(10)

def main():
    try:
        while True:
            ####---send message----
            # print('wait for connection...')
            # conn, client_addr = tcpServerSocket.accept()
            # print('connection form ', client_addr)
            # while True:
            #     conn.send(('[%s]' % ctime()).encode('utf-8'))
            #     print(f'send:{ctime()}')
            #     time.sleep(1)
            ####---receive  message----
            print('Waiting for connection...')
            conn, client_addr = tcpServerSocket.accept()
            print('Connection from ', client_addr)
            while True:
                data = conn.recv(1024)  # Receive up to 1024 bytes of data
                if not data:
                    break  # Exit loop if no data received
                received_str = data.decode('utf-8')  # Decode the received bytes as UTF-8 string
                print("Received:", received_str)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()

 esp32代码:

from socket import *
import sys


def Wifi_connect(ssid_c, password_c):
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    
    # 检测是否已经连接WiFi
    if wlan.isconnected():
        print('\033[31m当前esp32已连接WiFi,ip地址:%s \033[0m'%(wlan.ifconfig()[0]))
        print('是否需要连接新的WiFi?(Y or N)', end = '')
        ans = input()
        if ans.find("N") != -1 or ans.find("n") != -1:
            return 0
    
    # 搜索WiFi
    print('search WiFi...')
    ssid_all = wlan.scan() # 这个扫描优先级很高,扫描的时候 定时器无法执行
 
    for ssid in ssid_all:
        if ssid_c == bytes.decode(ssid[0]):
            #print('find WiFi!')
            break
    else:
        print('no WiFi found!')
        sys.exit(-1)
        return 0
    
    # 连接WiFi
    try:
        wlan.connect(ssid_c, password_c)
        print('connecting...')
        #delay(2500) # 为了得到ip地址
        while not wlan.isconnected():
            pass
        print('\033[31mWiFi名:%s IP地址:%s \033[0m'%(ssid_c,wlan.ifconfig()[0]))
    except:
        print('WiFi密码不正确!请更改密码后再次运行程序!')
        sys.exit(-1)
        
    return wlan

def main():
    host = "47.109.57.12"
    post = 8000
    addr = (host, post)
    tcpClient = socket(AF_INET, SOCK_STREAM)
    
    print('Ip address of ' + host + ' is ' + host)
    addr = (host, post)
    tcpClient.connect(addr)
    print('connetion success...')
    ###---recive message----
#     while True:
#         data = tcpClient.recv(1024).decode()
#         print(data)
    ###---send message----
    try:
        while True:
            message = input("Enter message to send: ")
            tcpClient.send(message.encode('utf-8'))  # Send the message to the server
    except KeyboardInterrupt:
        print("Client terminated.")
    finally:
        tcpClient.close()

if __name__ == '__main__':
    wlan = Wifi_connect('your wlan name','your wlan pwd') # WiFi名,密码
    main()

 

参考【学习笔记】如何使用python的socket包实现本地与云服务器通信 - 知乎 (zhihu.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值