Class: RCon::Client::Connection
- Inherits:
-
Object
- Object
- RCon::Client::Connection
- Defined in:
- lib/rcon/client/connection.rb
Overview
Wraps a TCP socket for sending and receiving RCON packets.
Instance Method Summary collapse
-
#close ⇒ Object
Closes the connection.
-
#initialize(host, port) ⇒ Connection
constructor
A new instance of Connection.
-
#open ⇒ self
Opens the TCP connection.
- #receive_packet ⇒ Packet
- #send_packet(packet) ⇒ Object
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
#close ⇒ Object
Closes the connection.
27 28 29 |
# File 'lib/rcon/client/connection.rb', line 27 def close @socket&.close end |
#open ⇒ self
Opens the TCP connection.
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. end |
#receive_packet ⇒ Packet
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. end |
#send_packet(packet) ⇒ Object
32 33 34 |
# File 'lib/rcon/client/connection.rb', line 32 def send_packet(packet) @write_mutex.synchronize { @socket.write(packet.encode) } end |