欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 基于Twisted框架的文件夾網(wǎng)絡(luò)傳輸源碼

 更新時(shí)間:2016年08月28日 23:08:27   作者:ian  
這篇文章主要介紹了Python 基于Twisted框架的文件夾網(wǎng)絡(luò)傳輸源碼,需要的朋友可以參考下

由于文件夾可能有多層目錄,因此需要對其進(jìn)行遞歸遍歷。

本文采取了簡單的協(xié)議定制,定義了五條命令,指令Head如下:
Sync:標(biāo)識(shí)開始同步文件夾
End:標(biāo)識(shí)結(jié)束同步
File:標(biāo)識(shí)傳輸?shù)奈募ㄏ鄬β窂剑?br /> Folder:標(biāo)志文件夾(相對路徑)
None:文件內(nèi)容

每條命令以CMB_BEGIN開始,以CMB_END結(jié)束。

客戶端需要對接收緩沖做解析,取出一條一條的指令,然后根據(jù)指令的Head做相應(yīng)的處理,比如創(chuàng)建文件夾、寫入文件等。

下面是服務(wù)端的代碼:

from twisted.internet import reactor
from twisted.internet.protocol import Protocol,Factory
from twisted.protocols.basic import LineReceiver
import os
import struct
 
BUFSIZE = 4096
 
class SimpleLogger(Protocol):
  def connectionMade(self):
    print 'Got connection from', self.transport.client
 
  def connectionLost(self, reason):
    print self.transport.client, 'disconnected'
 
  def dataReceived(self, line):
    print line
    self.transport.write("Hello Client, I am the Server!\r\n")
 
    self.transport.write("CMB_BEGIN")
    self.transport.write("Sync")
    self.transport.write("CMB_END")
    self.send_file_folder('server')
 
  def send_file_folder(self,folder):
    '''send folder to the client'''
    for f in os.listdir(folder):
      sourceF = os.path.join(folder, f)
      if os.path.isfile(sourceF):      
        print 'File:',sourceF[7:]
        self.transport.write("CMB_BEGIN")
        self.transport.write("File:" + sourceF[7:])
        self.transport.write("CMB_END")
        fp = open(sourceF,'rb')
        while 1:
          filedata = fp.read(BUFSIZE)
          if not filedata: break
          else:
            self.transport.write("CMB_BEGIN")
            self.transport.write(filedata)
            print 'send size:::::::::',len(filedata)
            self.transport.write("CMB_END")
        fp.close()
        self.transport.write("CMB_BEGIN")
        self.transport.write("End")
        self.transport.write("CMB_END")
      if os.path.isdir(sourceF):
        print 'Folder:',sourceF[7:]
        self.transport.write("CMB_BEGIN")
        self.transport.write("Folder:" + sourceF[7:])
        self.transport.write("CMB_END")
        self.send_file_folder(sourceF)
 
factory = Factory()
factory.protocol = SimpleLogger
reactor.listenTCP(1234, factory)
reactor.run()

Server在收到Client的某個(gè)信號(hào)之后(此代碼中,當(dāng)Client隨便向Server發(fā)送任何內(nèi)容都可),Server即會(huì)調(diào)用send_file_folder將sever文件夾下的內(nèi)容全部發(fā)送給客戶端。

服務(wù)端運(yùn)行結(jié)果如下:

下面是客戶端的代碼:

from twisted.internet.selectreactor import SelectReactor
from twisted.internet.protocol import Protocol,ClientFactory
from twisted.protocols.basic import LineReceiver
import os
from struct import *
 
reactor = SelectReactor()
protocol = Protocol()
prepare = 0
filename = ""
sourceDir = 'client'
recvBuffer = ''
 
def delete_file_folder(src):
  '''delete files and folders'''
  if os.path.isfile(src):
    try:
      os.remove(src)
    except:
      pass
  elif os.path.isdir(src):
    for item in os.listdir(src):
      itemsrc = os.path.join(src,item)
      delete_file_folder(itemsrc) 
    try:
      os.rmdir(src)
    except:
      pass
 
def clean_file_folder(src):
  '''delete files and child folders'''
  delete_file_folder(src)
  os.mkdir(src)
 
def writefile(filename,data):
  print 'write file size:::::::::',len(data)
  fp = open(filename,'a+b')
  fp.write(data)
  fp.close()
 
class QuickDisconnectedProtocol(Protocol):
  def connectionMade(self):
    print "Connected to %s."%self.transport.getPeer().host
    self.transport.write("Hello server, I am the client!\r\n")
  def dataReceived(self, line):
    global prepare
    global filename
    global sourceDir
    global recvBuffer
 
    recvBuffer = recvBuffer + line
    self.processRecvBuffer()
 
  def processRecvBuffer(self):
    global prepare
    global filename
    global sourceDir
    global recvBuffer
 
    while len(recvBuffer) > 0 :
      index1 = recvBuffer.find('CMB_BEGIN')
      index2 = recvBuffer.find('CMB_END')
 
      if index1 >= 0 and index2 >= 0:
        line = recvBuffer[index1+9:index2]
        recvBuffer = recvBuffer[index2+7:]
 
        if line == 'Sync':
          clean_file_folder(sourceDir)
 
        if line[0:3] == "End":
          prepare = 0
        elif line[0:5] == "File:":
          name = line[5:]
          filename = os.path.join(sourceDir, name)
          print 'mk file:',filename
          prepare = 1
        elif line[0:7] == "Folder:":
          name = line[7:]
          filename = os.path.join(sourceDir, name)
          print 'mkdir:',filename
          os.mkdir(filename)
        elif prepare == 1:
          writefile(filename,line)
      else:
        break 
 
class BasicClientFactory(ClientFactory):
  protocol=QuickDisconnectedProtocol
  def clientConnectionLost(self,connector,reason):
    print 'Lost connection: %s'%reason.getErrorMessage()
    reactor.stop()
  def clientConnectionFailed(self,connector,reason):
    print 'Connection failed: %s'%reason.getErrorMessage()
    reactor.stop()
 
reactor.connectTCP('localhost',1234,BasicClientFactory())
reactor.run()

客戶端提取出來自Server的指令,當(dāng)提取出Sync指令時(shí),則將sourceDir目錄清空,然后根據(jù)后續(xù)的指令,跟Server的文件夾進(jìn)行同步。

客戶端運(yùn)行結(jié)果如下:

需要注意的地方:
Client寫入文件時(shí),需要以二進(jìn)制的方式打開文件,否則,在傳輸二進(jìn)制文件時(shí)可能出現(xiàn)錯(cuò)誤或?qū)е挛募p壞。

經(jīng)過測試,代碼可以正常的運(yùn)行,文件夾同步成功,文本文件、圖像和其他類型的二進(jìn)制文件均可正常傳輸。

相關(guān)文章

  • python利用scatter繪畫散點(diǎn)圖

    python利用scatter繪畫散點(diǎn)圖

    這篇文章主要介紹了python利用scatter繪畫散點(diǎn)圖,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下,希望對你的學(xué)習(xí)有所幫助
    2022-06-06
  • 淺析Python中將單詞首字母大寫的capitalize()方法

    淺析Python中將單詞首字母大寫的capitalize()方法

    這篇文章主要介紹了淺析Python中將單詞首字母大寫的capitalize()方法,是Python入門中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-05-05
  • Python中functools模塊函數(shù)解析

    Python中functools模塊函數(shù)解析

    這篇文章主要介紹了Python中functools模塊的常用函數(shù)解析,分別講解了functools.cmp_to_key,functools.total_ordering,functools.reduce,functools.partial,functools.update_wrapper和functools.wraps的用法,需要的朋友可以參考下
    2017-03-03
  • python使用cv2庫、下載opencv庫的方法

    python使用cv2庫、下載opencv庫的方法

    這篇文章主要介紹了python使用cv2庫、下載opencv庫的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • python并發(fā)爬蟲實(shí)用工具tomorrow實(shí)用解析

    python并發(fā)爬蟲實(shí)用工具tomorrow實(shí)用解析

    這篇文章主要介紹了python并發(fā)爬蟲實(shí)用工具tomorrow實(shí)用解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • python 列表,數(shù)組,矩陣兩兩轉(zhuǎn)換tolist()的實(shí)例

    python 列表,數(shù)組,矩陣兩兩轉(zhuǎn)換tolist()的實(shí)例

    下面小編就為大家分享一篇python 列表,數(shù)組,矩陣兩兩轉(zhuǎn)換tolist()的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • python代碼能做成軟件嗎

    python代碼能做成軟件嗎

    在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于把python代碼做成軟件的方法,有興趣的朋友們可以閱讀下。
    2020-07-07
  • python中關(guān)于decimal使用出現(xiàn)的一些問題

    python中關(guān)于decimal使用出現(xiàn)的一些問題

    這篇文章主要介紹了python中關(guān)于decimal使用出現(xiàn)的一些問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • python基礎(chǔ)之停用詞過濾詳解

    python基礎(chǔ)之停用詞過濾詳解

    這篇文章主要介紹了python基礎(chǔ)之停用詞過濾詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python基礎(chǔ)的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-04-04
  • pandas刪除重復(fù)數(shù)據(jù)簡單方法

    pandas刪除重復(fù)數(shù)據(jù)簡單方法

    這篇文章主要給大家介紹了關(guān)于pandas刪除重復(fù)數(shù)據(jù)的簡單方法,在數(shù)據(jù)處理過程中常常會(huì)遇到重復(fù)的問題,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-07-07

最新評論