module Takumi::ServerListPing

Constants

NEXT_STATUS
PORT
PROTOCOL_VERSION
VERSION

Public Instance Methods

ping(server_address = 'localhost', port = PORT, timeout: 60) click to toggle source
# File lib/takumi/server_list_ping.rb, line 12
def ping(server_address = 'localhost', port = PORT, timeout: 60)
  handshake = Takumi::ServerListPing::Handshake.create({
    server_address: server_address,
    port:           port
  })
  status_request = Takumi::ServerListPing::StatusRequest.create

  socket = TCPSocket.open(handshake.server_address, handshake.port)
  socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
  socket.write(handshake.to_s)
  socket.write(status_request.to_s)
  socket.flush

  packets = "".encode(Encoding::BINARY)

  begin
    Timeout.timeout(timeout) do
      loop do
        buf = socket.recv(1024)
        break if buf.empty? or socket.closed?
        packets << buf
      end
    end
  rescue Timeout::Error
    # ok
  end
  Takumi::ServerListPing::StatusResponse.decode(packets)
ensure
  socket.close if socket
end