Python Socket Transfer File

Source: Internet
Author: User
Tags rar unpack

The sender can continuously send new files, and the receiving end can receive new files continuously.

For example: send-side input: E:\visio.rar, the receiver will be saved by default as E:\new_visio.rar, support multiple concurrency, the implementation of the following;

Receiving end:

Method One:

#-*-coding:utf-8-*-ImportSocket,time,socketserver,struct,os,threadhost='192.168.50.74'Port=12307s=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#Defining socket TypesS.bind ((Host,port))#IP and port number to be monitored by the binding, tuple formatS.listen (1) defConn_thread (connection,address): whileTrue:Try: Connection.settimeout (600) Fileinfo_size=struct.calcsize ('128SL') BUF=connection.recv (fileinfo_size)ifBuf#If you do not add this if, the first file transfer will automatically go to the next sentenceFilename,filesize =struct.unpack ('128SL', buf) Filename_f= Filename.strip ('\00') Filenewname= Os.path.join ('e:\\',('New_'+filename_f)) Print 'File New name is%s, FileSize is%s'%(filenewname,filesize) recvd_size= 0#define the file size that was receivedFile = Open (Filenewname,'WB')                Print 'Stat Receiving ...'                 while  notRecvd_size = =FileSize:ifFilesize-recvd_size > 1024: Rdata= CONNECTION.RECV (1024) Recvd_size+=Len (rdata)Else: Rdata= Connection.recv (FileSize-recvd_size) Recvd_size=filesize file.write (rdata) file.close ()Print 'Receive Done'                #connection.close ()        exceptsocket.timeout:connection.close () whiletrue:connection,address=s.accept ()Print('Connected by', address)#thread = Threading. Thread (target=conn_thread,args= (connection,address)) #使用threading也可以    #Thread.Start ()Thread.start_new_thread (Conn_thread, (connection,address)) S.close ()

Method Two:

#-*-coding:utf-8-*-ImportSocket,time,socketserver,struct,oshost='192.168.50.74'Port=12307ADDR=(Host,port)classMyrequesthandler (socketserver.baserequesthandler):defhandle (self):Print('Connected from:', self.client_address) whiletrue:fileinfo_size=struct.calcsize ('128SL')#defines the file information. 128s indicates that the file name is 128bytes long and L represents an int or log file type, where the file sizeSelf.buf =self.request.recv (fileinfo_size)ifSELF.BUF:#If you do not add this if, the first file transfer will automatically go to the next sentenceSelf.filename,self.filesize =struct.unpack ('128SL', Self.buf)#according to the 128SL unpacking file information, the same as the client side of the packaging rules                Print 'FileSize is:', Self.filesize,'filename size is:', Len (self.filename)#file name length is 128, greater than the actual file lengthSelf.filenewname = Os.path.join ('e:\\',('New_'+ self.filename). Strip ('\00'))#use Strip () to remove extra empty characters that are attached when packaging                PrintSelf.filenewname,type (self.filenewname) recvd_size= 0#define the file size that was receivedFile = Open (Self.filenewname,'WB')                Print 'Stat Receiving ...'                 while  notRecvd_size = =self.filesize:ifSelf.filesize-recvd_size > 1024: Rdata= SELF.REQUEST.RECV (1024) Recvd_size+=Len (rdata)Else: Rdata= Self.request.recv (Self.filesize-recvd_size) Recvd_size=self.filesize file.write (rdata) file.close ()Print 'Receive Done'        #self.request.close ()Tcpserv=socketserver.threadingtcpserver (ADDR, Myrequesthandler)Print('waiting for connection ...') Tcpserv.serve_forever ()

Send side:

#-*-coding:utf-8-*-Importsocket,os,structs=Socket.socket (Socket.af_inet,socket. Sock_stream) S.connect (('192.168.50.74', 12307)) whileTrue:filepath= Raw_input ('Please Enter chars:\r\n')    ifOs.path.isfile (filepath): Fileinfo_size=struct.calcsize ('128SL')#Defining packaging Rules        #define header information, including file name and file sizeFhead = Struct.pack ('128SL', Os.path.basename (filepath), Os.stat (filepath) st_size) s.send (fhead)Print 'Client filepath:', filepath#with open (filepath, ' RB ') as FO: There is a problem sending the file, and after sending it, something will be sent over.FO = open (filepath,'RB')         whileTrue:filedata= Fo.read (1024)            if  notFiledata: Breaks.send (Filedata) fo.close ()Print 'send over ...'        #s.close ()

Python Socket Transfer File

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.