Sample Python Socket transfer file
- 2020-05-19 05:11:56
- OfStack
The sending end can send new files all the time, and the receiving end can receive new files all the time.
For example, if the sender enters: e:\ visio.rar, the receiver will be saved as e:\ new_visio.rar by default.
The receiver:
Method 1:
#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os,thread
host='192.168.50.74'
port=12307
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # define socket type
s.bind((host,port)) # The binding needs to be monitored Ip And the port number, tuple format
s.listen(1)
def conn_thread(connection,address):
while True:
try:
connection.settimeout(600)
fileinfo_size=struct.calcsize('128sl')
buf = connection.recv(fileinfo_size)
if buf: # If I don't add this if In the first 1 Once the file transfer is completed, it will automatically go down 1 other
filename,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 # Defines the size of the file received
file = open(filenewname,'wb')
print 'stat receiving...'
while not recvd_size == filesize:
if filesize - 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()
except socket.timeout:
connection.close()
while True:
connection,address=s.accept()
print('Connected by ',address)
#thread = threading.Thread(target=conn_thread,args=(connection,address)) # use threading Can also be
#thread.start()
thread.start_new_thread(conn_thread,(connection,address))
s.close()
Method 2:
#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os
host='192.168.50.74'
port=12307
ADDR=(host,port)
class MyRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
print('connected from:', self.client_address)
while True:
fileinfo_size=struct.calcsize('128sl') # Define file information. 128s Means file name 128bytes Long, l said 1 a int or log File type, in this case the file size
self.buf = self.request.recv(fileinfo_size)
if self.buf: # If I don't add this if In the first 1 Once the file transfer is completed, it will automatically go down 1 other
self.filename,self.filesize =struct.unpack('128sl',self.buf) # According to the 128sl Unpack file information, and client The packaging rules for the end are the same
print 'filesize is: ',self.filesize,'filename size is: ',len(self.filename) # The length of the file name is 128 Greater than the actual length of the file name
self.filenewname = os.path.join('e:\\',('new_'+ self.filename).strip('\00')) # use strip() Remove any extra empty characters that are attached when packaging
print self.filenewname,type(self.filenewname)
recvd_size = 0 # Defines the size of the file received
file = open(self.filenewname,'wb')
print 'stat receiving...'
while not recvd_size == self.filesize:
if self.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()
The sender:
#-*- coding: UTF-8 -*-
import socket,os,struct
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.50.74',12307))
while True:
filepath = raw_input('Please Enter chars:\r\n')
if os.path.isfile(filepath):
fileinfo_size=struct.calcsize('128sl') # Define packaging rules
# Defines file header information, including file name and file size
fhead = 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 with sending the file this way, and it will be sent again when it is finished 1 Go over something
fo = open(filepath,'rb')
while True:
filedata = fo.read(1024)
if not filedata:
break
s.send(filedata)
fo.close()
print 'send over...'
#s.close()