server
import socket
import struct
import json
while True:
soc = socket.socket()
soc.bind(('192.168.31.233', 8001))
soc.listen(3)
print('等待客户端连接')
conn,addr=soc.accept()
user = conn.recv(65535)
user = str(user, encoding='utf8')
pwd = conn.recv(65535)
pwd = str(pwd, encoding='utf8')
if user == 'admin' and pwd == '123':
conn.send(b'true')
print('有个客户端连接上了',addr,'登陆成功')
while True:
try:
data=conn.recv(65535)
data = str(data,encoding='utf8')
if data:
with open('D:\python\课程相关文件.zip','rb') as f: ##随便本地一个文件
data = f.read()
dic={'size':len(data)}
dic_bytes=(json.dumps(dic)).encode('utf-8')
head_count=struct.pack('i',len(dic_bytes))
conn.send(head_count)
conn.send(dic_bytes)
conn.send(data)
except Exception:
break
else:
conn.send(b'false')
print('账号或密码错误')
conn.close()
client
import socket
import struct
import json
while True:
soc = socket.socket()
soc.connect(('192.168.31.233', 8001))
user = input('请输入账号')
soc.send(user.encode('utf-8'))
pwd = input('请输入密码')
soc.send(pwd.encode('utf8'))
t_or_f = soc.recv(65535)
if str(t_or_f,encoding='utf8') == 'true':
choice=input('是否下载:')
if choice == 'y':
soc.send(choice.encode('utf-8'))
head_dic_len=soc.recv(4)
head_l=struct.unpack('i',head_dic_len)[0]
dic_byte=soc.recv(head_l)
head=json.loads(dic_byte)
l=head['size']
count=0
data_total=b''
print('下载中')
while count<l:
if l<65535:
data=soc.recv(l)
else:
if l-count>=65535:
data=soc.recv(65535)
else:
data=soc.recv(l-count)
data_total+=data
count+=len(data)
with open(r'D:\python\test\qwe.zip','wb') as f:
f.write(data_total)
f.flush()
print('已完成')
else:
print('取消下载')
elif str(t_or_f,encoding='utf8') == 'false':
print('账号密码错误')
soc.close()
可以在