python: example of socket transferring large files

  • 2020-05-24 05:48:01
  • OfStack

Files can be transferred, but compare the files before and after the transfer: socket_test.txt, with some non-1 to server code at the end:


#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import time
'''
 Waiting for the connection 
 Waiting to send file 
 Read the data 
 Write to a file and save 
 Waiting for the connection 
'''
import socket
import threading
import time
import struct


def function(newsock, address):
  FILEINFO_SIZE = struct.calcsize('128sI')
  ''' Define the size of the file information (including the file name and file size). 128s On behalf of 128 a char[] (file name), I On behalf of 1 a integer or long (file size) '''
  while 1:
    try:
      fhead = newsock.recv(FILEINFO_SIZE)
      filename, filesize = struct.unpack('128sI', fhead)
      ''' Unpack the received database according to the packaging rules 128sI'''
      print "address is: ", address
      print filename, len(filename), type(filename)
      print filesize
      #filename = 'new_'+filename.strip('\00') #  Naming a new file new_ Transmitted file 
      filename = filename.strip('\00')
      fp = open(filename, 'wb') #  Create a new file and prepare to write 
      restsize = filesize
      print "recving..."
      while 1:
        if restsize > 102400: #  If the remaining packets are greater than 1024 , go to 1024 The packet 
          filedata = newsock.recv(10240)
        else:
          filedata = newsock.recv(restsize)
          fp.write(filedata)
          #break
        if not filedata:
          break
        fp.write(filedata)
        restsize = restsize - len(filedata) #  Calculate the remaining packet size 
        if restsize <= 0:
          break
      fp.close()
      print "recv succeeded !!File named:", filename
    except Exception, e:
      print unicode(e).encode('gbk')
      print "the socket partner maybe closed"
      newsock.close()
      break
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #  create tcp The connection 
sock.bind(('10.240.146.82', 8887)) #  On port and ip
sock.listen(5) #  Listening to the 
while True:
  newsock, address = sock.accept()
  print "accept another connection"
  tmpThread = threading.Thread(target=function, args=(newsock, address)) #  If a file is received, the thread is created 
  tmpThread.start() #  The thread of execution 
print 'end'

Client code:


#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
'''
 Enter the file name and upload it 
'''
import socket
import time
import struct
import os
f = open('socket_test.txt', 'wb')

for i in range(1000000):
  f.write('for socket test, the line number is : ' + str(i) + '\n')

f.close()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(50)
e = 0
try:
  sock.connect(('10.240.146.82', 8887))
  print 'connect...'
except socket.timeout, e:
  print 'timeout', e
except socket.error, e:
  print 'error', e
except e:
  print 'any', e
if not e:
  #while (1):
    #filename = raw_input('input your filename------->') #  Input file name 
  filename = 'socket_test.txt'
  FILEINFO_SIZE = struct.calcsize('128sI') #  Encoding format size 
  fhead = struct.pack('128sI', filename, os.stat(filename).st_size) #  Pack according to the rules 
  sock.send(fhead) #  Send file basic information data 
  fp = open(filename, 'rb')
  fp2 = open('local_test.txt','wb')
  i = 0
  while 1: #  Send a file 
    filedata = fp.read(10240)
    if not filedata:
      break
    sock.sendall(filedata)
    fp2.write(filedata)
    print i
    i = i + 1
  print "sending over..."
  fp.close()
  fp2.close()


Related articles: