python 上传下载文件
server.py #!/usr/bin/env python # -*- coding:utf-8 -*- import SocketServer import os class MySocketServer(SocketServer.BaseRequestHandler): def handle(self): filename_dir = '/home/feng/feng' conn = self.request data = conn.recv(1024) filename,filename_size = data.strip().split('|') print filename,filename_size recv_size = 0 file_dir=os.path.join(filename_dir,filename) f = open(file_dir,'w+') while True: if int(filename_size) != recv_size : data = conn.recv(1024) recv_size += len(data) print int(filename_size),recv_size f.write(data) else: break # else: # data = conn.recv(int(filename_size) - recv_size) # print int(filename_size) - recv_size # break print 'upload successed.......' if __name__ == '__main__': ip_port = ('127.0.0.1',55555) server = SocketServer.ThreadingTCPServer(ip_port,MySocketServer) server.serve_forever() ======================================= client.py #!/usr/bin/env python # -*- coding:utf-8 -*- import socket import os client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip_port = ('127.0.0.1',55555) client.connect(ip_port) while True: filepath = raw_input('请输入方法和上传路径:/root/1.txt: ') filename_size = os.stat(filepath).st_size filename = os.path.basename(filepath) print '#####################' print filepath,filename_size print '#####################' client.send(filename + '|' + str(filename_size)) send_size = 0 f = open(filepath,'r') Flag = True while Flag: if filename_size != send_size: data = f.read(1024) send_size += len(data) client.send(data) else: Flag=False f.close() client.close()