【问题标题】:Suppress nil response from Ruby method抑制来自 Ruby 方法的 nil 响应
【发布时间】:2015-01-08 16:09:02
【问题描述】:

我的任务是修改现有的 Ruby 脚本,但我的 Ruby 知识充其量只是基本的...... 我需要添加一种方法来检查服务器的端口是否打开。如果是,脚本应该继续做它正在做的任何事情。如果没有,它应该退出。

我应用了以下方法,取自Ruby - See if a port is open

def is_port_open?
  @host = "localhost"
  @port = "8080"
  begin
    Timeout::timeout(1) do
      begin
        s = TCPSocket.new(@host, @port)
        s.close
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        return "port closed :("
      end
    end
  rescue Timeout::Error
  end
  return "problem with timeout?"
end

这个方法似乎工作得很好,除非在端口打开时返回“nil”。我如何抑制任何输出(除非有错误)?

提前致谢!

【问题讨论】:

  • 在我看来,除非端口关闭,否则它将始终返回 "problem with timeout?"。返回nil是什么意思?
  • 您应该考虑更改方法的名称。 Ruby 中的编码约定是以“?”结尾的方法。将返回在条件语句中使用的真值或假值。不知道这会返回 String 的人可能会尝试在条件语句中使用它,结果却发现它总是通过。 (2 美分)

标签: ruby tcp nagios


【解决方案1】:

是否只需要检查一个条件(端口打开):

require 'timeout'
require 'socket'

def is_port_open? host, port
  @host = host || "localhost"
  @port = port || "8080"
  begin
    Timeout::timeout(1) do
      begin
        s = TCPSocket.new(@host, @port)
        s.close
        return true # success
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        return false # socket error 
      end 
    end 
  rescue Timeout::Error
  end 
  return false # timeout error
end

is_port_open? 'localhost', 8080
#⇒ true
is_port_open? 'localhost', 11111
#⇒ false

现在由您决定在发生错误等情况下返回什么。请注意,另一种选择是让异常传播给调用者。这个函数会更短一些,但你需要在调用者中处理异常。

【讨论】:

  • 谢谢!看来我最初的问题是我通过使用“puts”来调用该方法...... o.0(因此结果被打印出来)。
猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多