标签:成功 进阶 save put for utf8 run tcp pass
import socketserver
import json
import struct
class Mytcp(socketserver.BaseRequestHandler):
def handle(self):
try:
while True:
data_path = self.request.recv(1024)
data = str(data_path,encoding='utf8')
print(data_path)
with open(data,'rb') as f:
data = f.read()
dic = {'size':len(data)}
dic_b = bytes(json.dumps(dic).encode('utf-8'))
obj = struct.pack('i',len(dic_b))
self.request.send(obj)
self.request.send(dic_b)
self.request.send(data)
if len(data) == 0:
return
except Exception:
pass
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1',8009),Mytcp)
server.serve_forever()
from db import db_handler
from conf import setting
import os
import struct
import json
import socket
user_auth = {'user':None}
def register():
username = input('请输入账号')
pwd = input('密码')
flg = db_handler.read(username)
if not flg:
dic = {'username':username,'pwd':pwd}
db_handler.save(username,dic)
print('用户创建成功')
else:
print('用户已存在')
def login():
username = input('请输入账号')
pwd = input('密码')
data = db_handler.read(username)
if data:
if data['pwd'] == pwd:
print('登录成功')
user_auth['user'] = username
else:
print('用户不存在')
def upload():
address = input('请输入要上传的地址')
name = input('请输入名字')
data = db_handler.read('downlist')
data[name] = address
db_handler.save('downlist',data)
print('上传成功')
def download():
path_dic = db_handler.read('downlist')
for i in path_dic:
print(i)
dic_name = input('请输入你要下载的文件')
if dic_name not in path_dic:
print('没有此文件')
return
dic_path = path_dic[dic_name]
s = socket.socket()
s.connect(('127.0.0.1',8009))
s.send(dic_path.encode('utf8'))
print('下载中')
head_dic_len = s.recv(4)
head_l = struct.unpack('i', head_dic_len)[0]
dic_byte = s.recv(head_l)
head = json.loads(dic_byte)
l = head['size']
count = 0
data_total = b''
print('下载中')
while count < l:
if l < 65535:
data = s.recv(l)
else:
if l - count >= 65535:
data = s.recv(65535)
else:
data = s.recv(l - count)
data_total += data
count += len(data)
path = os.path.join(setting.DB_PATH,'Download',dic_name)
with open(path,'wb') as f:
f.write(data_total)
print('下载完成')
s.close()
def run():
msg = '''
1.注册
2.登录
3.上传
4.下载'''
go = {'1':register,'2':login,'3':upload,'4':download}
while True:
print(msg)
choice = input('请输入功能,q退出')
if choice == 'q':
break
if choice not in go:
continue
go.get(choice)()
run()
from conf import setting
import os
import json
def save(username,dic):
path = os.path.join(setting.DB_PATH,f'{username}.json')
with open(path,'w',encoding='utf8') as f:
json.dump(dic,f)
def read(username):
path = os.path.join(setting.DB_PATH,f'{username}.json')
if not os.path.exists(path):
return False
else:
with open(path,'r',encoding='utf8') as f:
data = json.load(f)
return data
标签:成功 进阶 save put for utf8 run tcp pass
原文地址:https://www.cnblogs.com/oxtime/p/11494525.html