loopやTCPServerに時間制限をかける

「timeout」を要求し、


timeout(秒数) {
loop { } #何もしない無限ループ
}
のように書くと、指定した秒数が経過した後、
例外(TimeoutError)が発生します。


具体的には、次のように使用します。

require "timeout"

#10秒間、クライアントを待つサーバープログラム
server = TCPServer.new(server_port_number)
client = nil
begin
timeout(10) {
client = server.accept
}
client.print "あなたがクライアントですね。わたしはサーバーです。"
client.close
rescue TimeoutError
puts "クライアントからのリクエストがありませんでした。"
end



■参考
[ruby-list:17260] Re: TCPserver の受付時間制限
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/17260


タイムアウトの秒数を指定する - Ruby例文辞典
http://www.openspc2.org/reibun/Ruby/time/006/index.html


まつもと直伝 プログラミングのオキテ 第16回 ネットワーク・プログラミング(ソケット編):ITpro
http://itpro.nikkeibp.co.jp/article/COLUMN/20071031/285990/?ST=oss&P=2