开发者

Socket in Ruby blindly hangs when trying to check an offline server

I use the following code to check the server status of a certain game server to see if the game server is online.

  begin
    sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
    sockaddr = Socket.sockaddr_in(game_server.gameserver_port, game_server.gameserver_hostname)
    sock.connect(sockaddr)
    server_status.status = 1
  rescue
    server_status.status = 0
  end

However it seems that the code blindly hangs up on the line without proceeding anywhere sock.connect(sockaddr) and does not throw an error when there's no services listening on that port. Is there a better way to do thi开发者_运维问答s in Ruby?


Could timeout be a good solution?

require 'timeout'

begin 
    timeout(5) do
        # socket stuff...
    end
rescue Timeout::Error
    puts "Timed out!"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜