class Srcon::Connection

Attributes

host[R]
port[R]
socket[R]

Public Class Methods

new(host, port, password = nil) click to toggle source

@param [String] host The host the server is listening on @param [Integer] port The port the server is listening on @param [String] password The password for authentication

# File lib/srcon/connection.rb, line 12
def initialize(host, port, password = nil)
  @host = host
  @port = port
  @id   = rand(Process.pid)

  connect!(password)
end

Public Instance Methods

receive() click to toggle source

@return [Srcon::Packet] The deconstructed packet received from the socket

# File lib/srcon/connection.rb, line 21
def receive
  Srcon::Packet.from_message(*socket.recvmsg)
end
send(message, type = Srcon::Packet::SERVERDATA_EXECCOMMAND) click to toggle source

@param [String] message A message to send to the server @param [Integer] type The type of message

@return [Integer] The number of bytes that were sent

# File lib/srcon/connection.rb, line 29
def send(message, type = Srcon::Packet::SERVERDATA_EXECCOMMAND)
  packet = Srcon::Packet.new(message, type, @id)
  @id += 1
  socket&.sendmsg(packet.to_b)
end

Private Instance Methods

connect!(password = nil) click to toggle source
# File lib/srcon/connection.rb, line 37
def connect!(password = nil)
  @socket = TCPSocket.new(host, port)

  return unless password

  # Authenticate if a password was provided
  send(password, Srcon::Packet::SERVERDATA_AUTH)

  response = receive

  raise AuthenticationFailure.new("Failed RCON auth to #{host}:#{port}") unless response.body == 'Authenticated.'
end