python——基础篇-简易文件上传
post_server
import socket import os sk=socket.socket() address=('127.0.0.1',8000) sk.bind(address) sk.listen(3) print('waiting...') BASE_DIR=os.path.dirname(os.path.abspath(__file__)) while 1: conn,addr=sk.accept() while 1: data=conn.recv(1024) cmd,filename,filesize=str(data,'utf-8').split('|') path=os.path.join(BASE_DIR,'post',filename) filesize=int(filesize) f=open(path,'ab') has_receive=0 while has_receive!=filesize: data=conn.recv(1024) f.write(data) has_receive+=len(data) f.close()
post_client:
import socket import os sk=socket.socket() address=('127.0.0.1',8000) sk.connect(address) BASE_DIR=os.path.dirname(os.path.abspath(__file__)) while True: inp=input('>>>').strip() cmd,path=inp.split('|') path = os.path.join(BASE_DIR,path) filename = os.path.basename(path) file_size = os.stat(path).st_size file_info = 'post|%s|%s' %(filename,file_size) sk.sendall(bytes(file_info, 'utf-8')) f=open(path, 'rb') data = f.read(1024) has_sent = 0 while has_sent!=file_size: data = f.read(1024) sk.sendall(data) has_sent += len(data) f.close() print('上传成功')