Python写一个简单的FTP

##

FTP v1.0版,仅实现文件上传,防止粘包,打印进度条,正在写v2版
Server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os,socketserver

class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
cmd,filename=self.request.recv(1024).decode().split()
print('Recv:',cmd,filename)
if os.path.isfile(filename):
file_size=os.path.getsize(filename)
print('file size:',file_size)
self.request.send(str(file_size).encode()) #send file size to client
client_ack=self.request.recv(1024) #wait for client ack
print('Client ACK:',client_ack.decode())
f=open(filename,'rb')
for line in f:
self.request.send(line)
print('server send success:',filename)
f.close()
except ValueError as e:
print('error,please retry:',e)
except ConnectionResetError as e:
print('error:',e)


if __name__ == "__main__":
Host,Port='localhost',999
server=socketserver.TCPServer((Host,Port),MyHandler)
server.serve_forever()

Client:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import sys
import socket,os
client=socket.socket()
client.connect(('localhost',999))

while True:
try:
action=input('Input action and filename:')
cmd,filename=action.split()
if len(action) <1:continue
client.send(action.encode())
file_size=int(client.recv(1024).decode())
ack=client.send(b'Already!')
received_size=0
f=open(filename,'wb')
def progressbar():
percentage = received_size/file_size
num = int(percentage*100)
view = '\r %d%%[%-100s]%d%%'%(0,'#'*num,100)
sys.stdout.write(view)
sys.stdout.flush()
while received_size < file_size:
data=client.recv(1024)
received_size+=len(data)
f.write(data)
progressbar()
else:
print('Recv done')
f.close()
os.system('dir')
except ValueError as e:
print('error:',e)

client.close()

运行效果:
这里写图片描述

赏一瓶快乐回宅水吧~
-------------本文结束感谢您的阅读-------------