構建輕量級檔案同步系統:Server 端採 asyncore 異步 I/O 接收檔案;Client 端用 pyinotify 監聽目錄變更,多執行緒佇列發送。核心在於自訂二進位協定封裝檔案元資料,確保傳輸可靠性。
# 表頭:網路位序
head_packet_format = "!LL128s128sL" # 路徑長、檔名長、路徑、檔名、檔案大小
head_packet_size = struct.calcsize(head_packet_format) # 268 bytes
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()
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
ssl.wrap_socket)systemd / supervisor 管理服務生命週期