server端:
import socket import os sk = socket.socket() address = ('127.0.0.1',8000) sk.bind(address) sk.listen(3) print('writing............') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) while True: conn,addr = sk.accept() # print(addr) while True: data = conn.recv(1024) #开始接收 cmd,filename,file_size = str(data,'utf8').split('|') path = os.path.join(BASE_DIR,'yuan',filename) file_size = int(file_size) f = open(path,'ab') has_receive = 0 while has_receive != file_size: data = conn.recv(1024) f.write(data) has_receive +=len(data) f.close() conn.close() sk.close()
client端:
import socket import os sk = socket.socket() address = ('127.0.0.1',8000) print(sk) sk.connect(address) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) while True: inp = input('>>>').strip()#post|123.jpg 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,'utf8')) f = open(path, 'rb') has_sent = 0 while has_sent != file_size: data = f.read(1024) sk.sendall(data) has_sent +=len(data) f.close() print('上传成功!!!!') sk.close()
上传结果:
先运行server端:
再运行client端:然后上传文件
本次上传文件,所上传的文件以及文件目录都在server端client端同意目录下进行