服务端server.py
import os
import json
import struct
import socketserver
class MyServer(socketserver.BaseRequestHandler):
# 重写handle消息的方法
def handle(self):
file_msg = self.recv_msg()
if file_msg['operate'] == 'download':
self.download(file_msg)
# 接收消息
def recv_msg(self, encoding='utf-8'):
dict_len_msg = self.request.recv(4)
dict_len = struct.unpack('i', dict_len_msg)[0]
file_msg = self.request.recv(dict_len).decode(encoding)
file_msg = json.loads(file_msg)
return file_msg
# 发送消息
def send_msg(self, dic, encoding='utf-8'):
str_dic = json.dumps(dic)
byte_dic = str_dic.encode(encoding)
dic_len = len(byte_dic)
byte_len = struct.pack('i', dic_len)
self.request.send(byte_len)
self.request.send(byte_dic)
# 发送文件
def send_file(self, dic, file_path):
with open(file_path, 'rb') as f:
while dic['filesize'] > 2048:
content = f.read(2048)
self.request.send(content)
dic['filesize'] -= len(content)
else:
content = f.read()
self.request.send(content)
# 下载处理
def download(self, file_msg):
file_name = file_msg['filename']
file_path = os.path.join('./source', file_name)
dic = {}
if os.path.isfile(file_path):
dic['filesize'] = os.path.getsize(file_path)
dic['isfile'] = True
self.send_msg(dic)
self.send_file(dic, file_path)
else:
dic['isfile'] = False
self.send_msg(dic)
server = socketserver.ThreadingTCPServer(('127.0.0.1', 5060), MyServer)
server.serve_forever()
客户端client.py
import json
import struct
import socket
def send_msg(sk, dic, encoding='utf-8'):
str_dic = json.dumps(dic)
byte_dic = str_dic.encode(encoding)
dic_len = len(byte_dic)
byte_len = struct.pack('i', dic_len)
sk.send(byte_len)
sk.send(byte_dic)
def recv_msg(sk, encoding='utf-8'):
dict_len_msg = sk.recv(4)
dict_len = struct.unpack('i', dict_len_msg)[0]
file_msg = sk.recv(dict_len).decode(encoding)
file_msg = json.loads(file_msg)
return file_msg
def recv_file(sk, dic, filename):
if dic['isfile']:
with open(r'./dest/' + filename, 'wb') as f:
while dic['filesize'] > 2048:
content = sk.recv(2048)
f.write(content)
dic['filesize'] -= len(content)
else:
content = sk.recv(dic['filesize'])
f.write(content)
dic['filesize'] -= len(content)
else:
print("您要下载的文件不存在")
if __name__ == '__main__':
# 定义一个客户端,连接服务器
tcp_client = socket.socket()
tcp_client.connect(('127.0.0.1', 5060))
# 下载文件
filename = input("请输入要下载的文件:")
dic = {'filename': filename, 'operate': 'download'}
send_msg(tcp_client, dic)
dic = recv_msg(tcp_client)
recv_file(tcp_client, dic, filename)
# 关闭客户端
tcp_client.close()
标签:文件,socketserver,self,len,dic,send,file,msg,下载
From: https://www.cnblogs.com/saiya6/p/16949685.html