从client端控制上传文件到server端
server端
import socket,os address=('127.0.0.1',8000) sk=socket.socket() print(sk) sk.bind(address) sk.listen(5) BASE_DIR=os.path.dirname(os.path.abspath(__file__)) while True: print('waitting connect...') conn,addr = sk.accept() while True: data=conn.recv(1024) cmd,filename,filesize=str(data,'utf-8').split('|') path=os.path.join(BASE_DIR,'document01',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()
client端
import socket,os sk = socket.socket() #建立tcp连接 print(sk) 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') has_sent=0 while has_sent !=file_size: data=f.read(1024) sk.sendall(data) has_sent+=len(data) f.close() print('上传成功!')
在client端输入 post|01.png ,01.png 文件就能上传到server端的指定目录document01