2012-03-27 197 views
2

如何處理Ruby Net :: SFTP傳輸中斷如網絡斷開?Ruby Net :: SFTP傳輸中斷處理

當我運行示例代碼並在傳輸過程中網絡斷開連接時,應用程序保持運行狀態。

require 'net/sftp' 

Net::SFTP.start("testing","root",:timeout=>1) do |sftp| 
    begin 
     sftp.download!("testfile_100MB", "testfile_100MB") 
    rescue RuntimeError =>e 
     puts e.message 
    end 
end 
+0

在你的程序被調用爲腳本的情況下,這很少是一個問題,net :: sftp有默認的超時時間,但它是用於連接的初始階段,我想。因此,如果建立的連接掛起,則需要從父線程或另一個進程(保姆)中斷它。可能是解決這個問題最簡單的方法。如果您的應用程序運行時間長於線程,則是解決此問題的最佳方法。 – Istvan 2012-11-22 07:09:13

回答

0

Net-SFTP類依賴於基礎連接的Net-SSH類。在上面的例子中,SSH連接嘗試維護自己,因此代碼繼續執行直到被SSH認爲失敗。 :timeout參數僅適用於初始連接。

4

如果下載看起來沒有響應,您可以創建另一個線程來觀察下載進度並使應用程序崩潰。由於網:: SFTP,您可以在自定義處理程序傳遞給download!方法,你可以設置觀察者線程這樣的:

class CustomHandler 
    def extend_time 
    @crash_time = Time.now + 30 
    end 

    # called when downloading has started 
    def on_open(downloader, file) 
    extend_time 
    downloader_thread = Thread.current 
    @watcher_thread = Thread.new{ 
     while true do 
     if Time.now > @crash_time 
      downloader_thread.raise "Downloading appears unresponsive. Network disconnected?" 
     end 
     sleep 5 
     end 
    } 
    end 

    # called when new bytes are downloaded 
    def on_get(downloader, file, offset, data) 
    extend_time 
    end 

    # called when downloading is completed 
    def on_close(downloader, file) 
    @watcher_thread.exit 
    end 
end 

而且不要忘記在這樣的定製處理器來傳遞:

sftp.download!(remote_path, local_path, :progress => CustomHandler.new)