python傳輸檔案最重要的有兩步: 1).將要傳輸的檔案的資訊發送過去,包括檔案包,大小以及其它資訊; 2).發送端讀取檔案內容並發送過去,接受端將緩衝裡面的內容寫入檔案. 發送端:from socket import * import os import struct ADDR = ('192.168.1.103',8000) BUFSIZE = 1024 filename = 'client.py' FILEINFO_SIZE=struct.calcsize('128s32sI8s') sendSock = socket(AF_INET,SOCK_STREAM) sendSock.connect(ADDR) fhead=struct.pack('128s11I',filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0) sendSock.send(fhead) fp = open(filename,'rb') while 1: filedata = fp.read(BUFSIZE) if not filedata: break sendSock.send(filedata) fp.close() sendSock.close() 接收端: # -*- coding: cp936 -*- from socket import * import struct ADDR = ('192.168.1.103',8000) BUFSIZE = 1024 FILEINFO_SIZE=struct.calcsize('128s32sI8s') recvSock = socket(AF_INET,SOCK_STREAM) recvSock.bind(ADDR) recvSock.listen(True) print "wait..." conn,addr = recvSock.accept() print "send from ",addr fhead = conn.recv(FILEINFO_SIZE) filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',fhead) #print filename,temp1,filesize,temp2 print filename,len(filename),type(filename) print filesize filename = 'new_'+filename.strip('\00') #... fp = open(filename,'wb') restsize = filesize while 1: if restsize > BUFSIZE: filedata = conn.recv(BUFSIZE) else: filedata = conn.recv(restsize) if not filedata: break fp.write(filedata) restsize = restsize-len(filedata) if restsize == 0: break fp.close() conn.close() recvSock.close() print "Finished" 代碼中,將檔案資訊採用struct的方式傳送過去.接收端接收並unpack.整個過程發送和接受各兩次,這便是整個的過程. |