萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 異步檔案同步伺服器實作:asyncore + pyinotify 雙端架構

構建輕量級檔案同步系統:Server 端採 asyncore 異步 I/O 接收檔案;Client 端用 pyinotify 監聽目錄變更,多執行緒佇列發送。核心在於自訂二進位協定封裝檔案元資料,確保傳輸可靠性。

協定封裝格式

# 表頭:網路位序
head_packet_format = "!LL128s128sL"  # 路徑長、檔名長、路徑、檔名、檔案大小
head_packet_size = struct.calcsize(head_packet_format)  # 268 bytes

Server 端核心邏輯

class RequestHandler(asyncore.dispatcher):
    def __init__(self, sock, chunk_size=1024):
        asyncore.dispatcher.__init__(self, sock)
        self.chunk_size = chunk_size
        self.data_to_write = []

    def handle_read(self):
        # 1. 讀取表頭
        data = self.recv(head_packet_size)
        filepath_len, filename_len, filepath, filename, filesize = \
            struct.unpack(head_packet_format, data)
        filepath = filepath[:filepath_len].decode().strip('\x00')
        filename = filename[:filename_len].decode().strip('\x00')
        fullpath = os.path.join('../perfdata', filepath, filename)

        # 2. 確保目錄存在
        os.makedirs(os.path.dirname(fullpath), exist_ok=True)
        self.fd = open(fullpath, 'wb')

        # 3. 分塊接收檔案內容
        remaining = filesize
        while remaining > 0:
            chunk = self.recv(min(self.chunk_size, remaining))
            if not chunk: break
            self.fd.write(chunk)
            self.fd.flush()
            remaining -= len(chunk)
        self.fd.close()

Client 端架構

  • 主執行緒:pyinotify.WatchManager + Notifier 監聽 IN_CREATE/IN_MODIFY/IN_DELETE 事件
  • 發送執行緒:從 Queue 取出事件,構造表頭 + 檔案內容,透過 TCP 發送
  • 斷線重連、檔案鎖定重試、增量傳輸(可結合 rsync 算法)

部署依賴

# Server
pip install pyinotify  # 僅 Client 需要
# Python 內建 asyncore, struct, socket, threading

# Client (Linux)
sudo apt-get install python-pyinotify
# 或 pip install pyinotify

擴充方向

  • 加入 TLS 加密傳輸(ssl.wrap_socket)
  • 實現斷點續傳(記錄已傳輸位移)
  • 支援目錄結構同步(遞迴建立子目錄)
  • 整合 systemd / supervisor 管理服務生命週期
copyright © 萬盛學電腦網 all rights reserved