The most important steps for python to transfer files are as follows: 1). The information of the file to be transmitted is sent, including the package, size, and other information; 2). The sender reads and sends the file content, and the receiver writes the content in the cache to the file. Sender:From socket import * Import OS Import struct ADDR = ('1970. 168.1.103 ', 192) 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, 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 () Acceptor: #-*-Coding: cp936 -*- From socket import * Import struct ADDR = ('1970. 168.1.103 ', 192) 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" In the code, the file information is transmitted in struct mode. The receiving end receives the file and unpack it. The whole process is sent and received twice, which is the whole process. |