Use socket in the struck to achieve the client sends
Server:
# - * - Coding: UTF-. 8 - * - Import Socket, Time, SocketServer, struct, OS, _Thread Host = '127.0.0.1' Port = 12307 S = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # define socket type s.bind ((host, port)) # bind need Ip and port to listen on, tuple format s.listen (1) DEF conn_thread (Connection, address): the while True: the try: connection.settimeout (600) fileinfo_size = struct.calcsize ( '12sl') # 12s represent 12 characters, l represents a long integer buf = connection.recv (fileinfo_size) IF buf: # if not after the if, the first file transfer is complete automatically go to the next one, you need to get the file size information before they can proceed filename, filesize = struct.unpack ( '12sl ', buf) filename_f = filename.decode ( "utf-8 "). strip ( '\ 00') # C language '\ 0' is an ASCII code 0 characters in python represents the null character occupy a position too = the os.path.join filenewname ( 'E: \\', os.path.basename (filename_f)) Print (U 'File Name:% s, file size: S%'% (filenewname, filesize)) recvd_size = 0 # defines the received file size file Open = (filenewname, 'WB') Print (U "start transmission file content") the while == Not recvd_size filesize: IF filesize - recvd_size> 1024: RDATA = connection.recv (1024) recvd_size = len + (RDATA) the else: RDATA = Connection.recv(filesize - recvd_size) recvd_size filesize = a file.write (RDATA) File.close () Print ( 'the receive DONE') # Connection.close () the except socket.timeout: connection.close() while True: print(u"开始进入监听状态") 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()
Client:
# - * - Coding: UTF-. 8 - * - Import Socket, OS, struct S = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s.connect (( '127.0.0.1', 12307)) the while True: filepath = input ( 'enter file to transfer the absolute path: \ R & lt \ n-') Print (type (filepath)) Print (len (filepath.encode ( "UTF-. 8"))) IF the os.path.isfile (filepath ): #fileinfo_size = struct.calcsize ( '20sl') rule # define packaged # definition file header information, including file name and file size fhead = struct.pack ( '12sl', filepath.encode ( "utf-8"), os .stat (filepath) .st_size) Print (the os.stat (filepath) .st_size) s.send (fhead) Print (U 'file path:', filepath) # with Open (filepath, 'RB') AS FO:So send the file in question, will be made after the completion of sending something in the past FO = Open (filepath, 'RB') the while True: Filedata = FO.read(1024) if not filedata: BREAK s.send (Filedata) fo.close () Print (U 'transmission success') # S.CLOSE ()
The service side effects:
Client results