Python Transfer files

Source: Internet
Author: User
Tags unpack osclass

Transfer file Simple version

Server side:

Import Socketimport structimport Jsonimport osshare_dir = R ' C:\py3Project\ lu fei \ Third module \ Chapter II Network programming \05_ file transfer \ Simple version \server\share '  Ip_port = (' 127.0.0.1 ', 8999) def bytes2human (n): Symbols = (' K ', ' M ', ' G ', ' T ', ' P ', ' E ') prefix = {} for I, S in Enumerate (symbols): # << left shift one means multiply by 2 that is 1 << 1=2, two bits means 4 that is 1 << 2=4, # 10 bits means 1024 is 1 <&lt ;            10=1024 is 2 of the n-th square prefix[s] = 1 << (i + 1) * for s in reversed (symbols): If n >= prefix[s]:    Value = Float (n)/prefix[s] return '%.2f%s '% (value, s) return "%SB"% ndef get (conn,file_name): # 3, read the way to open the file, read the contents of the file sent to the client # The first step: make a fixed-length header print (' get ') try:header_dict = {' file_name ': fil        E_name, ' MD5 ': ' xxx ', ' file_size ': Os.path.getsize (Os.path.join (Share_dir, file_name))}         Header_json = Json.dumps (header_dict, ensure_ascii= ' False ', indent=2) header_bytes = Header_json.encode (' Utf-8 ')      # Step Two: Send the length of the header first  Conn.send (Struct.pack (' I ', Len (header_bytes)) # Step three: Resend Header Conn.send (header_bytes) # Fourth step: Send real data again    With open (Os.path.join (Share_dir, file_name), ' RB ') as-f:for line-in-f:conn.send (line)     Except Exception as E:print (e) def put (Conn, file_name): "" "Receive client upload file:P Aram Conn::p Aram file_name:  : Return: "" "# 2, open a new file in writing, receive the contents of the file sent by the client to the server new file # First step: The length of the first header Header_len = CONN.RECV (4) header_size = Struct.unpack (' i ', Header_len) [0] # Step two: Re-accept the header Header_json = Conn.recv (header_size). Decode (' Utf-8 ') # Step three: Parse from the header Description of the real data Header_dict = Json.loads (header_json) file_size = header_dict[' file_size '] file_name = header_dict[' F Ile_name '] Print (Os.path.join (Share_dir, file_name) # Fourth step: Receive real data, write to file with open (Os.path.join (Share_dir, File_na            ME), ' WB ') as F:recv_size = 0 while recv_size < File_size:line = CONN.RECV (1024)           F.write (line) Recv_size + = Len Print (' Total size:%s uploaded size:%s '% (Bytes2human (file_size), Bytes2human (Recv_size))) def run (): Server = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Server.bind (Ip_port) Server.listen (5) print (' starting ... ') while true:conn, addr = Server . Accept () print (addr) while True:try: # 1 Receive Command res = CONN.RECV (1024 # b ' Get a.txt ' if not Res:break # 2, parse command, extract corresponding command parameter Cmds = Res.decode (' utf-                    8 '). Split () # [GET, A.txt] if cmds[0] = = ' Get ': Get (conn, cmds[1]) # download file            # file_name = cmds[1] elif cmds[0] = = ' put ': put (conn, cmds[1]) # upload file Except Connectionreseterror: #适用于windows操作系统 break Conn.close () server.close () if __name__ = = ' _ _main__ ': Run ()

  

Client Side

  

#!/usr/bin/env Python3 #-*-coding:utf-8-*-import socketimport structimport jsonimport osshare_dir = R ' C:\py3Project\ Lu Fei \ third module \ Chapter II Network programming \05_ file transfer \ Simple version \client\download ' Ip_port = (' 127.0.0.1 ', 8999) def bytes2human (n): Symbols = (' K ', ' M ', ' G ', ' T ', ' P ', ' E ') prefix = {} for I, s in enumerate (symbols): # << left shift left one means multiply by 2 that's 1 << 1=2, two bits means 4 is 1 & lt;< 2=4, # 10 bits means 1024 is 1 << 10=1024 is 2 n prefix[s] = 1 << (i + 1) * Ten for S in revers    Ed (symbols): If n >= prefix[s]: value = float (n)/prefix[s] return '%.2f%s '% (value, s) Return "%SB"% ndef get (client, file_name): # 2, open a new file in a written way, the content of the file received by the server is written to the client's new file # The first step: the length of the first header is Header_len = CLIENT.RECV (4) header_size = Struct.unpack (' i ', Header_len) [0] # Step two: Re-receive header Header_json = CLIENT.RECV (header_size). Decode (' Utf-8 ') # Step three: Parse the description of real data from the header header_dict = Json.loads (header_json) file_size = header_dict[' file_size ' ] file_name = Header_dict[' file_name ' Print (Os.path.join (Share_dir, file_name)) # Fourth step: Receive real data, write to file with open (Os.path.join (Share_dir,            file_name), ' WB ') as F:recv_size = 0 while recv_size < File_size:line = CLIENT.RECV (1024) F.write (line) Recv_size + = Len (line) print (' Total size:%s downloaded size:%s '% (Bytes2human (file_size), b Ytes2human (recv_size)) def put (client, file_name): # Upload the file to the server print (' put ') Try:if not Os.path.isfile (OS.P            Ath.join (Share_dir, file_name)): Print (' file:%s is not exists '% Os.path.join (Share_dir, file_name))                 return else:file_size = Os.path.getsize (Os.path.join (Share_dir, file_name)) Header_dict = {            ' file_name ': file_name, ' MD5 ': ' xxx ', ' file_size ': file_size} Header_json = Json.dumps (header_dict, ensure_ascii= ' False ', indent=2) header_bytes = Header_json.encod E (' Utf-8 ') #Step two: First send the length of the header client.send (struct.pack (' I ', Len (header_bytes)) # Step three: Resend Header Client.send (head Er_bytes) # Fourth step: Send the real data again with open (Os.path.join (Share_dir, file_name), ' RB ') as F:fo R line on F:client.send (line) except Exception as E:print (e) def run (): client = Socket.s Ocket (socket.af_inet, socket. SOCK_STREAM) Client.connect (ip_port) while True: # 1, send command cmd = input (' >> '). Strip () # ' Get A.tx T ' if not cmd:continue client.send (Cmd.encode (' utf-8 ')) if Cmd.startswith (' Get '): Get (Clie  NT, Cmd.split () [1]) elif cmd.startswith (' put '): Put (client, Cmd.split () [1]) Client.close () if __name__ = = ' __main__ ': Run ()

 

Output results

Sever:starting ... (' 127.0.0.1 ', 19074) getgetc:\users\jingjing\pycharmprojects\py3project\ Lu Fei \ Third module \ Chapter II Network programming \05_ file transfer \ Simple version \server\ Share\3.jpeg Total size: 75.36K   uploaded Size: 1.00K total size: 75.36K   uploaded size: 2.00K ... Total size: 75.36K   uploaded size:75.36kclient:>> get 1.pptxc:\py3project\ road fly \ Third module \ Chapter II Network programming \05_ file transfer \ Simple version \client\download\ 1.pptx Total size: 970.93K   downloaded size: 1.00K Total size: 970.93K   downloaded size: 2.00K ... Total size: 970.93K   

  

Transfer files optimized version

Server side:

Import socketimport structimport jsonimport osclass tcpserver:ip_port = (' 127.0.0.1 ', 8999) request_queue_size = 5 allow_reuse_address = False Max_packet_size = 8192 Share_dir = R ' C:\py3Project\ lu fei \ Third module \ Chapter II Network programming \05_ file transfer \ Simple version \serve R\share ' Def __init__ (self, Address=ip_port, bind_and_activate=true): Self.server = Socket.socket (Socket.AF_INET , socket. SOCK_STREAM) if Bind_and_activate:try:self.server.bind (address) Self.ser Ver.listen (self.request_queue_size) print (' starting ... ') except Exception as E:s Elf.server.close () Raise e def get_request (self): "" "Get the request and client address from the        Socket. "" "Return Self.server.accept () def run (self): when True:self.conn, self.client_addr = self.               Get_request () print (' From client ', self.client_addr) while True:try:     # 1 Receive Command res = SELF.CONN.RECV (self.max_packet_size) # b ' Get a.txt ' if not res:                    Break # 2, Parse command, extract the corresponding command parameter CMDS = Res.decode (' Utf-8 '). Split () # [GET, A.txt] If Hasattr (self, cmds[0]): Func = GetAttr (self, Cmds[0]) func (cmd        S[1]) except Connectionreseterror: # applies to Windows operating system break Self.conn.close () Self.server.close () def put (self, file_name): "" "Receive client upload file:P Aram Conn::p Aram fil        E_name:: Return: "" "Print (' Get file%s '% file_name) # 2, open a new file as written, receive the contents of the file sent by the client to the new file on the server # First Step: Take the length of the header Header_len = SELF.CONN.RECV (4) header_size = Struct.unpack (' i ', Header_len) [0] # Step two: Re-receive the header Header_json = Self.conn.recv (header_size). Decode (' Utf-8 ') # Step three: Parse a description of the real data from the header Header_dic t = json.loads (HEADER_JSON) file_size = header_dict[' file_size '] file_name = header_dict[' file_name '] print (os.path.join            . Share_dir, file_name) # Fourth step: Receive the real data, write the file with open (Os.path.join (Self.share_dir, file_name), ' WB ') as F: recv_size = 0 while recv_size < File_size:line = Self.conn.recv (self.max_packet_siz                e) F.write (line) Recv_size + = Len (line) rate = recv_size/file_size * 100        Print (' Total size:%s uploaded:%%%.2f '% (Self.bytes2human (file_size), rate)) @staticmethod def bytes2human (n): Symbols = (' K ', ' M ', ' G ', ' T ', ' P ', ' E ') prefix = {} for I, s in enumerate (symbols): # <& Lt Move left one means multiply by 2, 1 << 1=2, two bits means 4 that is 1 << 2=4, # 10 bits means 1024 or 1 << 10=1024 is 2 n-th square prefix [s] = 1 << (i + 1) * Ten for S in reversed (symbols): If n >= prefix[s]: value = f Loat (n)/prefix[s]               Return '%.2f%s '% (value, s) return "%SB"% n def get (self, file_name): # 3, open the file in read mode, read the file                Content sent to client # First step: Make a fixed-length header print (' Send file%s '% file_name) try:header_dict = { ' file_name ': file_name, ' MD5 ': ' xxx ', ' file_size ': Os.path.getsize (Os.path.join (self.sh            Are_dir, file_name)} Header_json = Json.dumps (header_dict, ensure_ascii= ' False ', indent=2) Header_bytes = Header_json.encode (' utf-8 ') # Step two: First send the length of the header Self.conn.send (the Struct.pack (' I ', Len (he ader_bytes)) # Third step: Resend Header Self.conn.send (header_bytes) # Fourth step: Send real data again with open (Os.path.join (Self.share_dir, file_name), ' RB ') as F:for line in F:self.conn.send (line ) except Exception as E:print (e) if __name__ = = ' __main__ ': s = TCPServer () s.run ()

  

Client side:

Import socketimport structimport jsonimport osclass tcpclient:ip_port = (' 127.0.0.1 ', 8999) request_queue_size = 5 allow_reuse_address = False Max_packet_size = 8192 Share_dir = R ' C:\py3Project\ lu fei \ Third module \ Chapter II Network programming \05_ file transfer \ Simple version \clien T\download ' Def __init__ (self, Address=ip_port, connect=true): Self.client = Socket.socket (socket.af_inet, Socke T.sock_stream) if Connect:try:self.client.connect (address) except Exception            As E:self.client.close () Raise E def run (self): while True: # 1, Send command INP = input (' >> '). Strip () # ' Get a.txt ' if not inp:continue self.client.send (INP.E Ncode (' utf-8 ')) cmd = Inp.split () if hasattr (self, cmd[0]): func = Getatt  R (self, Cmd[0]) func (cmd[1]) client.close () @staticmethod def bytes2human (n): symbols = (' K ', ' M ', ' G ', ' T ', ' P', ' E ') prefix = {} for I, s in enumerate (symbols): # << left Shift left one represents multiply by 2 that is 1 << 1=2, and two bits represents        4 i.e. 1 << 2=4, # 10 bits means 1024 i.e. 1 << 10=1024 is 2 n prefix[s] = 1 << (i + 1) * 10                For s in reversed (symbols): If n >= prefix[s]: value = float (n)/prefix[s] Return '%.2f%s '% (value, s) return "%SB"% n def get (self, file_name): # 2, open a new file as written, write the contents of the file received by the server         Customer's new file # First step: Take the length of the header first Header_len = SELF.CLIENT.RECV (4) header_size = Struct.unpack (' i ', Header_len) [0]        # Step Two: Collect the header Header_json = Self.client.recv (header_size). Decode (' Utf-8 ') # Step three: Parse a description of the real data from the header Header_dict = Json.loads (header_json) file_size = header_dict[' file_size '] file_name = header_dict[' File_n Ame '] Print (Os.path.join (Self.share_dir, file_name)) # Fourth step: Receive the real data, write the file with open (Os.path.join (self.s Hare_dir, file_name), ' WB ') as F:recv_size = 0 while recv_size < File_size:line = Self.client.recv (self. max_packet_size) F.write (line) Recv_size + = Len (line) rate = Recv_size/file        _size * Print (' Total size:%s downloaded:%%%.2f '% (Self.bytes2human (file_size), rate)) def put (self, file_name): # Upload files to the server print (' put ') Try:if not Os.path.isfile (Os.path.join (Self.share_dir, file_name)            ): Print (' file:%s is not exists '% Os.path.join (Self.share_dir, file_name)) return                     Else:file_size = Os.path.getsize (Os.path.join (Self.share_dir, file_name)) Header_dict = {                    ' file_name ': file_name, ' MD5 ': ' xxx ', ' file_size ': file_size                } Header_json = Json.dumps (header_dict, ensure_ascii= ' False ', indent=2) Header_bytes = Header_jsOn.encode (' Utf-8 ') # Step two: First send the length of the header self.client.send (struct.pack (' I ', Len (header_bytes))) # Step Three: Resend the header self.client.send (header_bytes) # Fourth step: Send the real data again W ITH open (Os.path.join (Self.share_dir, file_name), ' RB ') as F:for line in F:sel    F.client.send (line) except Exception as E:print (e) if __name__ = = ' __main__ ': c = TCPClient () C.run ()

  

Output Result:

 

Sever:starting...from client  (' 127.0.0.1 ', 3500) send file 3.jpegget file 1.pptxc:\py3project\ road fly \ Third module \ Chapter II Network programming \05_ File transfer \ Simple version \server\share\1.pptx total size: 970.93K   uploaded:%0.82 ... Total size: 970.93K   uploaded:%99.96 total size: 970.93K   uploaded:%100.00client:c:/py3project/luffy/Third module/Chapter II network programming/05_ file transfer/simple version/client/ File_client.py>> get 3.jpegc:\py3project\ road fly \ Third module \ Chapter II Network programming \05_ file transfer \ Simple version \client\download\3.jpeg total size: 75.36K   downloaded:%10.62 ... Total size: 75.36K   Downloaded:%99.49 Total size: 75.36K   

  

  

Python Transfer files

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.