欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python单线程文件传输的实例(C/S)

程序员文章站 2023-08-17 12:31:21
客户端代码: #-*-encoding:utf-8-*- import socket import os import sys import mat...

客户端代码:

#-*-encoding:utf-8-*-
 
import socket
import os
import sys
import math
import time
 
def progressbar(cur, total):
 percent = '{:.2%}'.format(float(cur) / float(total))
 sys.stdout.write('\r')
 sys.stdout.write("[%-50s] %s" % (
       '=' * int(math.floor(cur * 50 / total)),
       percent))
 sys.stdout.flush()
 
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 file content
  sentlength = 0
  while sentlength < filesize:
   buflen = 1024
   buf = file.read(buflen)
   client.send(buf)
   sentlength += len(buf)
   process = int(float(sentlength) / float(filesize) * 100)
   progressbar(process, 100)
  client.recv(1024)
  file.close()
  timeend = time.clock()
  print "\r\nfinished, spent %d seconds" % (timeend - timestart)
 else:
  print "file doesn't exist"
 
targethost = raw_input("server ip address: ")
targetport = int(raw_input("server port: "))
 
while true:
 transferfile()

服务器端代码:

#-*-encoding:utf-8-*-
 
import socket
import threading
import os
import sys
import math
 
bindip = "0.0.0.0"
bindport = 9999
 
server = socket.socket(socket.af_inet, socket.sock_stream)
server.bind((bindip, bindport))
server.listen(1)
print "listening on %s:%d" % (bindip, bindport)
 
def progressbar(cur, total):
 percent = '{:.2%}'.format(float(cur) / float(total))
 sys.stdout.write('\r')
 sys.stdout.write("[%-50s] %s" % (
       '=' * int(math.floor(cur * 50 / total)),
       percent))
 sys.stdout.flush()
 
def checkfilename(originalfilename):
 extensionindex = originalfilename.rindex(".")
 name = originalfilename[:extensionindex]
 extension = originalfilename[extensionindex+1:]
 
 index = 1
 newnamesuffix = "(" + str(index) + ")"
 finalfilename = originalfilename
 if os.path.exists(finalfilename):
  finalfilename = name + " " + newnamesuffix + "." + extension
 while os.path.exists(finalfilename):
  index += 1
  oldsuffix = newnamesuffix
  newnamesuffix = "(" + str(index) + ")"
  finalfilename = finalfilename.replace(oldsuffix, newnamesuffix)
 return finalfilename
 
def handleclient(clientsocket):
 # receive file size
 filesize = int(clientsocket.recv(1024))
 # print "[<==] file size received from client: %d" % filesize
 clientsocket.send("received")
 # receive file name
 filename = clientsocket.recv(1024)
 # print "[<==] file name received from client: %s" % filename
 clientsocket.send("received")
 filename = checkfilename(filename)
 file = open(filename, 'wb')
 # receive file content
 print "[==>] saving file to %s" % filename
 receivedlength = 0
 while receivedlength < filesize:
  buflen = 1024
  if filesize - receivedlength < buflen:
   buflen = filesize - receivedlength
  buf = clientsocket.recv(buflen)
  file.write(buf)
  receivedlength += len(buf)
  process = int(float(receivedlength) / float(filesize) * 100)
  progressbar(process, 100)
 
 file.close()
 print "\r\n[==>] file %s saved." % filename
 clientsocket.send("received")
 
while true:
 client, addr = server.accept()
 print "[*] accepted connection from: %s:%d" % (addr[0], addr[1])
 
 clienthandler = threading.thread(target=handleclient, args=(client,))
 clienthandler.start()

运行结果示例:

服务器端:

python单线程文件传输的实例(C/S)

客户端(服务器端做了端口映射:59999->9999):

python单线程文件传输的实例(C/S)

以上这篇python单线程文件传输的实例(c/s)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。