服务器安装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()