赞
踩
我发现,如果不向cmd方法提供块,它将返回响应(假设telnet没有向您请求其他任何东西)。您可以一次发送所有命令(但将所有响应捆绑在一起)或执行多个调用,但必须执行嵌套块回调(否则我无法执行)。在require 'net/telnet'
class Client
# Fetch weather forecast for NYC.
#
# @return [String]
def response
fetch_all_in_one_response
# fetch_multiple_responses
ensure
disconnect
end
private
# Do all the commands at once and return everything on one go.
#
# @return [String]
def fetch_all_in_one_response
client.cmd("\nNYC\nX\n")
end
# Do multiple calls to retrieve the final forecast.
#
# @return [String]
def fetch_multiple_responses
client.cmd("\r") do
client.cmd("NYC\r") do
client.cmd("X\r") do |forecast|
return forecast
end
end
end
end
# Connect to remote server.
#
# @return [Net::Telnet]
def client
@client ||= Net::Telnet.new(
'Host' => 'rainmaker.wunderground.com',
'Timeout' => false,
'Output_log' => File.open('output.log', 'w')
)
end
# Close connection to the remote server.
def disconnect
client.close
end
end
forecast = Client.new.response
puts forecast
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。