服務器端
import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 獲取本機名
hostname = socket.gethostname()
# 獲取本機ip
ip = socket.gethostbyname(hostname)
server.bind(('192.168.43.52', 8000))
server.listen(5)
print('服務器啓動成功')
def receive_file(c_id):
try:
# 文件傳輸
with open("receve.png", "wb") as file:
while True:
# 接收數據
file_data = c_id.recv(1024)
# 數據長度不爲0寫入文件
if file_data:
file.write(file_data)
# 數據長度爲0表示下載完成
else:
print('傳輸完成')
break
# 下載出現異常時捕獲異常
except Exception as e:
print("下載異常", e)
# 無異常則下載成功
else:
print("下載成功")
def run(c_id):
com = input('please input')
# 這裏必須輸入1 客戶端纔開始傳輸文件
c_id.send(com.encode('utf-8'))
threading.Thread(target=receive_file, args=(client_id,)).start()
while True:
client_id, client_address = server.accept()
# print()
print(client_address, '連接成功')
threading.Thread(target=run, args=(client_id,)).start()
客戶端
# coding=utf-8
from picamera import PiCamera, Color
from time import sleep
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def send_file(file_path):
try:
# 數據傳輸
with open(file_path, "rb") as file:
while True:
# 讀取文件數據
file_data = file.read(1024)
# 數據長度不爲0表示還有數據
if file_data:
client.send(file_data)
# 數據爲0表示傳輸完成
else:
print("傳輸成功")
break
except Exception as e:
print("傳輸異常:", e)
ip = '192.168.43.52'
# 連接服務器
a=client.connect((ip, 8000))
print('connect successful')
file_path='/home/pi/Desktop/Photo.png'
while True:
recv_com = client.recv(1024).decode('utf-8')
print(recv_com)
if recv_com=='1':
send_file(file_path)
# 這裏需要設置傳輸完成後手動關閉本連接,要不然服務器會一直等待。
client.close()
break
client.close()
print('Done')
注意事項
遇到的最大一點錯誤就是,傳輸完成後沒有關閉連接,所以導致程序一直在運行沒有結束傳輸。
雖然客戶端使用了兩個線程,但是應該直接使用函數來存儲文件就歐克了