利用Socketserver实现简单的文件上传
#!/usr/bin/env python #coding:utf-8 import SocketServer import os class MyServer(SocketServer.BaseRequestHandler): def handle(self): base_path = ‘C:/temp‘ conn = self.request print ‘connected...‘ while True: pre_data = conn.recv(1024) #获取请求方法、文件名、文件大小 cmd,file_name,file_size = pre_data.split(‘|‘) #已经接收文件的大小 recv_size = 0 #上传文件路径拼接 file_dir = os.path.join(base_path,file_name) f = file(file_dir,‘wb‘) Flag = True while Flag: #未上传完毕, if int(file_size)>recv_size: #最多接收1024,可能接收的小于1024 data = conn.recv(1024) recv_size+=len(data) #上传完毕,则退出循环 else: recv_size = 0 Flag = False continue #写入文件 f.write(data) print ‘upload successed.‘ f.close() if __name__ == ‘__main__‘: instance = SocketServer.ThreadingTCPServer((‘127.0.0.1‘,9999),MyServer) instance.serve_forever()
#!/usr/bin/env python # coding:utf-8 __author__ = ‘aolens‘ import socket import sys import os ip_port = (‘127.0.0.1‘,9999) s = socket.socket() s.connect(ip_port) container = {‘key‘:‘‘,‘data‘:‘‘} while True: input = raw_input(‘path:‘) cmd,path = input.split(‘|‘) file_name = os.path.basename(path) file_size=os.stat(path).st_size s.send(cmd+"|"+file_name+‘|‘+str(file_size)) send_size = 0 f= file(path,‘rb‘) Flag = True while Flag: if send_size + 1024 >file_size: data = f.read(file_size-send_size) Flag = False else: data = f.read(1024) send_size+=1024 s.send(data) f.close() s.close()
客户端输出path的格式为:方法|路径
path:PUT|C:/oem8.log
查看上传文件路径
C:/temp
下,发现有了一个oem8.log
文件,上传成功
时间: 2024-10-25 02:11:00