Class: RCon::Client::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/rcon/client/connection.rb

Overview

Wraps a TCP socket for sending and receiving RCON packets.

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Connection

Returns a new instance of Connection.



9
10
11
12
13
# File 'lib/rcon/client/connection.rb', line 9

def initialize(host, port)
  @host = host
  @port = port
  @write_mutex = Mutex.new
end

Instance Method Details

#closeObject

Closes the connection.



27
28
29
# File 'lib/rcon/client/connection.rb', line 27

def close
  @socket&.close
end

#openself

Opens the TCP connection.

Returns:

  • (self)

Raises:



19
20
21
22
23
24
# File 'lib/rcon/client/connection.rb', line 19

def open
  @socket = TCPSocket.new(@host, @port)
  self
rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT, SocketError => e
  raise ConnectionError, e.message
end

#receive_packetPacket

Returns:

Raises:



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rcon/client/connection.rb', line 38

def receive_packet
  raw_size = @socket.read(4)
  raise ConnectionError, "connection closed by server" unless raw_size&.bytesize == 4

  size = raw_size.unpack1("l<")
  raw_body = @socket.read(size)
  raise ConnectionError, "connection closed by server" unless raw_body&.bytesize == size

  Packet.decode(raw_size + raw_body)
rescue Errno::ECONNRESET => e
  raise ConnectionError, e.message
end

#send_packet(packet) ⇒ Object

Parameters:



32
33
34
# File 'lib/rcon/client/connection.rb', line 32

def send_packet(packet)
  @write_mutex.synchronize { @socket.write(packet.encode) }
end