#-*-encoding:utf-8-*- Import socket Import OS Import Sys Import Math Import time Import threading def getfilesize (file): File.seek (0, OS. Seek_end) Filelength = File.tell () File.seek (0, 0) Return filelength def getfilename (Filefullpath): index = filefullpath.rindex (' \ \ ') If index = = 1: Return Filefullpath Else Return filefullpath[index+1:] Def transferfile (): Filefullpath = r "%s"% raw_input ("File path:"). Strip ("\") If Os.path.exists (Filefullpath): Timestart = Time.clock () File = open (Filefullpath, ' RB ') FileSize = GetFileSize (file) Client = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Client.connect ((Targethost, Targetport)) # Send File size Client.send (str (fileSize)) Response = CLIENT.RECV (1024) # Send file name Client.send (GetFileName (Filefullpath)) Response = CLIENT.RECV (1024) # Send Thread Count Client.send (str (threadcount)) Response = CLIENT.RECV (1024) # Send file Content For I in Range (ThreadCount): Filepartsender = Threading. Thread (Target=transferfilesubthread, args= (Filefullpath, i+1, fileSize)) Filepartsender.start () For I in Range (ThreadCount): Sem.acquire () Timeend = Time.clock () Print "Finished, spent%f seconds"% (Timeend-timestart) Else Print "File doesn ' t exist" def transferfilesubthread (Filefullpath, Threadindex, fileSize): Try Client = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Client.connect ((Targethost, Targetport)) Client.send (str (THREADINDEX)) CLIENT.RECV (1024) # Calculate start position and end position Filepartsize = Filesize/threadcount StartPosition = Filepartsize * (threadIndex-1) #print "Thread:%d, startposition:%d"% (Threadindex, startposition) endposition = filepartsize * threadIndex-1 if Threadindex = = ThreadCount: Endposition = fileSize-1 Filepartsize = Filesize-startposition File = open (Filefullpath, "RB") File.seek (startposition) Sentlength = 0 While Sentlength < filepartsize: Buflen = 1024 Lengthleft = Filepartsize-sentlength If Lengthleft < 1024: Buflen = Lengthleft BUF = File.read (Buflen) Client.send (BUF) Sentlength = Len (buf) File.close () Sem.release () Print "Part%d finished, size sent%d"% (Threadindex, sentlength) Except Exception, E: Print E Targethost = Raw_input ("Server IP Address:") targetport = Int (raw_input ("Server Port:") threadcount = Int (raw_input ("Thread count:") SEM = threading. Semaphore (0) While True: Transferfile () |