老男孩----上海校区
简易FTP
客户端端
import socket
import struct
import json
import os
class MYTCPCLIENT:
address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM
allow_reuse_address = False
max_packet_size = 8192
coding ='utf-8'
request_queue_size = 5
def __init__(self,server_address,connect = True):
self.server_address = server_address
self.socket = socket.socket(self.address_family,self.socket_type)
if connect:
try:
self.client\_connect()
except:
self.client\_close()
raise
def client\_connect(self):
self.socket.connect(self.server\_address)
def client\_close(self):
self.socket.close()
def run(self):
while True:
choice = input(">>>>:").strip()
if not choice:continue
f = choice.split()
cmd=f\[0\]
if hasattr(self,cmd):
func = getattr(self,cmd)
func(f)
def put(self,args):
cmd = args\[0\]
filename = args\[1\]
if not os.path.isfile(filename):
print('file:%s is not exists' %filename)
return
else:
filesize = os.path.getsize(filename)
head\_dic = {'cmd':cmd,'filename':os.path.basename(filename),'filesize':filesize}
head\_json=json.dumps(head\_dic)
head\_json\_bytes = bytes(head\_json,encoding=self.coding)
head\_struce = struct.pack('i',len(head\_json\_bytes))
self.socket.send(head\_struce)
self.socket.send(head\_json\_bytes)
send\_size = 0
with open(filename,'rb') as f:
for line in f:
self.socket.send(line)
send\_size+=len(line)
print(send\_size)
else:
print('下载成功')
client = MYTCPCLIENT(('127.0.0.1',8080))
client.run()
服务端
import socketserver
import struct
import json
import os
class FtpServer(socketserver.BaseRequestHandler):
coding='utf-8'
server_dir ='file_upload'
max_packet_size = 1024
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
def handle(self):
print(self.request)
while True:
data = self.request.recv(4)
data_len=struct.unpack('i',data)[0]
head_json= self.request.recv(data_len).decode(self.coding)
head_dic = json.loads(head_json)
cmd = head_dic['cmd']
if hasattr(self,cmd): # 判断这个对象中有没有这个属性
func=getattr(self,cmd) #获取对象属性值
func(head_dic)
def put(self,args):
flie_path = os.path.normpath(os.path.join(
self.BASE_DIR,
self.server_dir,
args['filename']
))
filesize=args['filesize']
recv_size = 0
print('------>',flie_path)
with open(flie_path,'wb') as f:
while recv_size <filesize:
recv_data = self.request.recv(self.max_packet_size)
f.write(recv_data)
recv_size += len(recv_data)
print('recvsize:%s filesize:%s' % (recv_size, filesize))
ftpserver = socketserver.ThreadingTCPServer(('127.0.0.1',8080),FtpServer)
ftpserver.serve_forever()
手机扫一扫
移动阅读更方便
你可能感兴趣的文章