2

如何处理 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
4

2 回答 2

4

您可以创建另一个线程来查看下载进度并在下载出现无响应时使应用程序崩溃。由于 Net::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)
于 2012-11-06T13:36:32.837 回答
0

Net-SFTP 类依赖于底层连接的 Net-SSH 类。在上面的示例中,SSH 连接尝试自行维护,因此代码会继续执行,直到被 SSH 视为失败。该:timeout参数仅适用于初始连接。

于 2012-08-29T08:21:16.857 回答