python 基於selectors庫實現文件上傳與下載

server.py

import selectors
import socket
import os
import time


BASE_DIR =os.path.abspath(os.path.dirname(__file__))

class selectFtpserver:
  def __init__(self):
    self.dic = {} # 創建空字典
    self.hasReceived = 0
    self.hasSend=0
    self.sel = selectors.DefaultSelector() # 生成一個select對象
    self.create_socket() #create_socket()是創建socket對象函數完成綁定功能
    self.hanle() #handle()函數完成循環監聽

  def create_socket(self):
    sock = socket.socket()
    sock.bind(('127.0.0.1', 8899))
    sock.listen()
    sock.setblocking(False)
    self.sel.register(sock, selectors.EVENT_READ, self.accept) # 把剛生成的sock連接對象註冊到select連接列表中,並交給accept函數處理
    print("服務端已打開,請連接客戶端")

  def hanle(self):
    while True:
      events = self.sel.select() # 默認是阻塞,有活動連接就返回活動的連接列表
      # 這裡看起來是select,其實有可能會使用epoll,如果你的系統支持epoll,那麼默認就是epoll
      # print("event==",events)
      for key, mask in events:
        callback = key.data # 去調accept函數
        callback(key.fileobj, mask) # key.fileobj就是readable中的一個socket連接對象

  def accept(self,sock, mask):
    conn, addr = sock.accept() # Should be ready
    print('accepted', conn, 'from', addr)
    conn.setblocking(False) # 設定非阻塞
    self.sel.register(conn, selectors.EVENT_READ, self.read) # 新連接註冊read回調函數
    self.dic[conn] = {} # 在空字典裡進行瞭conn賦值,self.dic={conn:{},}

  def read(self, conn, mask): # 接收瞭conn和mask
    try: # 加異常防止客戶端突然斷開
      if not self.dic[conn]: # 判斷self.dic[conn]裡面是否是空字典,如果是空字典,代表第一次進來
        print('====第一次進來')
        data = conn.recv(1024) # conn接收瞭客戶端發來的數據
        print("data==",str(data, encoding='utf-8'))
        cmd, filename,filesize = str(data, encoding='utf-8').split('|') # 把接收到客戶端發來的包解開拿到cmd,filename,filesize個信息
        self.dic = {conn: {"cmd": cmd, "filename": filename, "filesize": int(filesize)}} # 把拿到的cmd,filename,filesize信息放到self.dic字典裡去後程序返回到handle()函數裡的events繼續監聽
        print(self.dic)
        if cmd == 'put': # 如果接收的信息是put
          conn.send(bytes("OK", encoding='utf8')) # 給客戶端返回一條數據
        if self.dic[conn]['cmd'] == 'get':
          file = os.path.join(BASE_DIR, "upload", filename)

          if os.path.exists(file):
            print("文件存在的情況,返回YES給客戶端")
            filesize = os.path.getsize(file)
            self.dic[conn]['filesize'] = filesize
            print("self.dic",self.dic)
            send_info = '%s|%s' % ('YES', filesize)
            conn.send(bytes(send_info, encoding='utf8'))
          else:
            print("文件不存在情況下")
            send_info = '%s|%s' % ('NO', 0)
            conn.send(bytes(send_info, encoding='utf8'))
            self.dic[conn] = {} #文件不存在的情況下,要將清空字典
      else: # 如果不是空字典代表不是第一次進來
        print('不是第一次來的')
        print(self.dic)
        if self.dic[conn].get('cmd', None): # 對接收的命令進行分發判斷是put還是get
          cmd = self.dic[conn].get('cmd')
          if hasattr(self, cmd): # 如果cmd=put調用put函數,如果是cmd=get函數調用get函數
            func = getattr(self, cmd)
            func(conn)
          else:
            print("error cmd!")
            conn.close()
        else:
          print("error cmd!")
          conn.close()
    except Exception as e:
      print('斷開的客戶端信息是:', conn)
      self.sel.unregister(conn) # 如果沒有接收到數據做一個關閉解除
      conn.close()

    # put上傳函數
  def put(self, conn):
    fileName = self.dic[conn]['filename']
    fileSize = self.dic[conn]['filesize']
    # print("BASE_DIR",BASE_DIR)
    path = os.path.join(BASE_DIR, "upload", fileName) # 拿到要接收的信息
    # print(fileName,fileSize,path)

    recv_data = conn.recv(1024) # 接收客戶端上傳的數據1024字節
    self.hasReceived += len(recv_data) # 把接收的數據累加到變量self.hasReceived

    with open(path, 'ab') as f: # 打開文件
      f.write(recv_data) # 把接收的數據寫到文件裡去

    if fileSize == self.hasReceived: # 判斷文件大小跟接收大小是否一樣
      if conn in self.dic.keys(): # 如果文件大小跟接收大小一樣清空字典
        self.dic[conn] = {}
      self.hasReceived = 0 #S上傳結束之後,需要將self.hasReceived 重置成功
      print("%s 上傳完畢!" % fileName)

  def get(self,conn):
    fileName = self.dic[conn]['filename']
    file = os.path.join(BASE_DIR, "upload", fileName)
    # fileSize = os.path.getsize(file)
    fileSize=self.dic[conn]['filesize']

    data = conn.recv(1024) # conn接收瞭客戶端發來的數據
    dataOK = str(data, encoding='utf-8')

    if dataOK == 'OK':
      with open(file, 'rb') as f: # 打開文件
        while fileSize > self.hasSend: # 循環的發送文件給客戶端
          contant = f.read(1024)
          recv_size = len(contant)
          conn.send(contant)
          self.hasSend += recv_size
          s = str(int(self.hasSend / fileSize * 100)) + "%"
          print("正在下載文件: " + fileName + " 已經下載:" + s)

      if fileSize == self.hasSend: # 判斷文件大小跟接收大小是否一樣
        if conn in self.dic.keys(): # 如果文件大小跟接收大小一樣清空字典
          self.dic[conn] = {}
        print("%s 下載完畢!" % fileName)
        self.hasSend = 0

if __name__ == '__main__':
  selectFtpserver()

client.py

import socket
import os,sys
BASE_DIR=os.path.dirname(os.path.abspath(__file__))

class selectFtpClient:
  def __init__(self):
    self.args=sys.argv               #sys.argv在命令行輸入的參數,第一個參數默認文件名,第二個參數跟IP地址和端口
    if len(self.args)>1:              #如果大於1把第二個參數倆個值賦值給port
      self.port=(self.args[1],int(self.args[2]))
    else:
      self.port=("127.0.0.1",8899)        #如果沒有第二個參數默認取這個
    self.create_socket()               #
    self.command_fanout()              #進行命令分發
    self.mainPath = os.path.join(BASE_DIR, 'filename') # 獲取該客戶端下的filename路徑

  #create_socket函數創建socket對象連接服務端
  def create_socket(self):
    try:
      self.sk = socket.socket()
      self.sk.connect(self.port)
      print('連接FTP服務器成功!')
    except Exception as e:
      print("eroor:",e)

  #command_fanout()函數進行命令分發
  def command_fanout(self):
    while True:
      try:
        print("----------------welcome to ftp client-------------------")
        self.help_info()
        cmd_info = input('>>>請輸入操作命令:').strip() # put 12.png images
        if not cmd_info:
          continue
        cmd,file = cmd_info.split() ##按照空格分隔
        # print("命令是什麼", cmds)
        if cmd == "quit":
          break
        if hasattr(self, cmd):
          func = getattr(self, cmd)
          func(cmd,file)
          Tag = input("是否繼續進入ftp clinet,請選擇Y/N:").strip()
          if Tag.upper() == 'Y':
            continue
          else:
            break
        else:
          print('No such command ,please try again')
      except Exception as e: # server關閉瞭
        print('%s' % e)
        break

  def help_info(self):
    print ('''
       get + (文件名)  表示下載文件
       put + (文件名)  表示上傳文件
       quit       表示退出登錄
    ''')

  #put()上傳函數
  def put(self,cmd,file):
    if os.path.isfile(file):              #判斷本地文件是否存在
      fileName = os.path.basename(file)        #取出文件的名字
      fileSize = os.path.getsize(file)         #取出文件的大小
      fileInfo = '%s|%s|%s'%(cmd,fileName,fileSize) #給文件名字大小打包成fileInf
      self.sk.send(bytes(fileInfo, encoding='utf8')) #調用send方法把fileInf發給服務端
      recvStatus = self.sk.recv(1024)         #接收服務端返回的OK內容
      print('recvStatus' , recvStatus)
      hasSend = 0
      if str(recvStatus, encoding='utf8') == "OK":  #如果接收到服務端返回的OK
        with open(file, 'rb') as f:        #打開文件
          while fileSize > hasSend :       #循環的去上傳文件
            contant = f.read(1024)
            recv_size = len(contant)
            self.sk.send(contant)
            hasSend += recv_size
            s=str(int(hasSend/fileSize*100))+"%"
            print("正在上傳文件: "+fileName+" 已經上傳:" +s)
        print('%s文件上傳完畢' % (fileName,))
    else:
      print('要上傳的文件不存在')

  #get()下載函數
  def get(self,cmd,fileName):
    path = os.path.join(BASE_DIR, "download", fileName) # 拿到要接收的信息
    fileSize=0
    fileInfo = '%s|%s|%s' % (cmd, fileName, fileSize) # 給文件名字大小打包成fileInf
    print(fileInfo)
    self.sk.send(bytes(fileInfo, encoding='utf8')) # 調用send方法把fileInfo發給服務端

    recvdata = self.sk.recv(1024) # 接收服務端返回的是否存在文件內容
    recvStatus, fileSize = str(recvdata, encoding='utf-8').split('|')
    print("recvStatus==",recvStatus,fileSize)
    fileSize = int(fileSize)

    hasReceived = 0
    if recvStatus == "YES": # 如果接收到服務端返回的YES
      self.sk.send(bytes('OK', encoding='utf8')) # 通知服務端可以正常下載瞭

      while fileSize > hasReceived: # 循環的發送文件給客戶端
        recv_data = self.sk.recv(1024) # 接收客戶端上傳的數據1024字節
        hasReceived += len(recv_data) # 把接收的數據累加到變量self.hasReceived
        print("hasReceived",hasReceived)

        with open(path, 'ab') as f: # 打開文件
          f.write(recv_data) # 把接收的數據寫到文件裡去

        if fileSize == hasReceived: # 判斷文件大小跟接收大小是否一樣
          print("%s 下載完畢!" % fileName)
          recvStatus = 'YESS'
    else:
       print('要下載的文件不存在')


if __name__=='__main__':
  selectFtpClient()

以上就是python 基於selectors庫實現文件上傳與下載的詳細內容,更多關於python 上傳下載的資料請關註WalkonNet其它相關文章!

推薦閱讀: