python第37天小练习
作业:
编写cs架构的软件,实现客户端可以下载服务端的文件,如图片、视频、文本等
选做:
1、实现上传功能
2、服务端支持并发
3、阿里云服务器应用
服务端:
from socket import *
import subprocess
import struct
phone=socket(AF_INET,SOCK_STREAM)
phone.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
phone.bind(('127.0.0.1',808))
phone.listen(5)
while True:
conn,client_addr=phone.accept()
while True:
try:
data=conn.recv(1024)
if len(data) == 0:
break
data = data.decode('utf-8')
print("需要下载的文件地址:\n",data.decode('utf-8'))
cmd, file = data.split(' ',1)
if cmd == 'get':
try:
with open(file,'rb') as f:
data = f.read()
conn.send(struct.pack('i',len(data))+data)
except Exception:
conn.send('路径不存在'.encode('utf-8'))
else:
conn.send('命令不正确'.encode('utf-8'))
except Exception:
break
conn.close()
客户端:
import socket
import struct
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
print('=====下载数据=====')
while True:
msg=input("请输入下载地址>>>: ").strip()
if len(msg) == 0:continue
msg,file = msg.rsplit(' ',1)
phone.send(msg.encode('utf-8'))
top = phone.recv(4)
top_len = struct.unpack('i',top)
print(top_len)
total_size = 0
try:
with open(file,'wb') as f:
while total_size < top_len[0]:
recv_data=phone.recv(1024)
f.write(data)
total_size += len(recv_data)
print('下载成功!')
except Exception:
print('保存路径不存在')
phone.close()