2017-06-19 77 views
0

我正在致力於client-server文件共享以更新特定文件夾。客戶端使用tcp-socket連接到服務器並接收特定zip-file然後解壓縮。到目前爲止,我已經完成了這一工作,但我想比較兩個文件夾(客戶端和服務器)中的文件以檢查文件內容(即:更新文件)的差異,並且只在內容不同時才下載文件。使用tcp套接字比較客戶端和服務器之間的文件

我的代碼

客戶:

import socket 
import zipfile 
import os 

def main(): 
    host = '192.168.1.8' 
    port = 5000 
    s = socket.socket() 
    s.connect((host, port)) 
    with open('C:\\file.zip', 'wb') as f: 
     while True: 
      data = s.recv(1024) 
      if not data: 
       break 
      f.write(data) 
    zip_ref = zipfile.ZipFile('C:\\file.zip', 'r') 
    zip_ref.extractall('C:\\') 
    zip_ref.close() 
    os.remove('C:\\file.zip') 
    s.close() 

if __name__ == '__main__': 
    main() 

服務器:

import socket 
from threading import Thread 

def send_file(conn, filename): 
    with open(filename, 'rb') as f: 
     print 'Sending file' 
     data = f.read(1024) 
     while data: 
      conn.send(data) 
      data = f.read(1024) 
    print 'Finished sending' 
    conn.close() 


def main(): 
    host = '192.168.1.8' 
    port = 5000 
    s = socket.socket() 
    s.bind((host, port)) 
    s.listen(5) 
    while True: 
     c, addr = s.accept() 
     t = Thread(target=send_file, args=(c, 'C:\\file.zip')) 
     t.start() 

if __name__ == '__main__': 
    main() 

我迄今爲止嘗試:

我試過filecmp.dircmp但它只檢查不同的文件,而不是不同的文件內容,我也無法比較客戶端和服務器的文件夾。我還試圖通過文件loop並在每個文件上使用filecmp,但我也無法將它與來自服務器的同一文件進行比較。

有沒有一種有效的方法來做到這一點?

回答

1

不知道我知道您在使用filecmp來比較從服務器下載客戶端的內容之前。在這些情況下,通常有兩種方法:合併協議以檢查服務器中文件的修改日期(例如os.path.getmtime(file_name)),然後確保在客戶端下載文件時設置修改日期;要麼;讓客戶端請求哈希文件並在哈希不匹配時下載。

+0

謝謝!經過一些測試後,我終於按照你的建議使用'os.path.getmtime(filename)'來工作。我唯一擔心的是,我現在正在將'modified-date'從服務器發送到客戶端,並將其作爲'socket.recv(1024)'接收,這對所有情況都適用嗎?接收(1024)? –

+0

'getmtime'返回一個浮點數,根據這個其他答案,python中的浮點數爲64位:https://stackoverflow.com/questions/8216088/how-to-check-the-size-of-a-float- in-python,但這是一個時間戳,因此您將獲得的合理值將遠遠小於此值。 –

相關問題