class KRPC::Connection
A TCP Connection
.
Constants
- DEFAULT_SERVER_HOST
- DEFAULT_SERVER_RPC_PORT
- DEFAULT_SERVER_STREAM_PORT
Attributes
host[R]
port[R]
socket[R]
Public Class Methods
new(host, port)
click to toggle source
# File lib/krpc/connection.rb, line 16 def initialize(host, port) @host, @port = host, port end
Public Instance Methods
cleanup()
click to toggle source
# File lib/krpc/connection.rb, line 50 def cleanup; end
close()
click to toggle source
Close connection and clean up.
# File lib/krpc/connection.rb, line 36 def close if connected? socket.close cleanup true else false end end
connect()
click to toggle source
Connect and perform handshake.
# File lib/krpc/connection.rb, line 21 def connect if connected? then raise(ConnectionError, "Already connected") else @socket = TCPSocket.open(host, port) begin handshake rescue Exception => e close raise e end end self end
connected?()
click to toggle source
Return true
if connected to a server, false
otherwise.
# File lib/krpc/connection.rb, line 45 def connected? !socket.nil? && !socket.closed? end
handshake()
click to toggle source
# File lib/krpc/connection.rb, line 49 def handshake; end
protobuf_handshake(type, **attrs)
click to toggle source
# File lib/krpc/connection.rb, line 52 def protobuf_handshake(type, **attrs) send_message PB::ConnectionRequest.new(type: type, **attrs) resp = receive_message PB::ConnectionResponse raise(ConnectionError, "#{resp.status} -- #{resp.message}") unless resp.status == :OK resp end
receive_message(msg_type)
click to toggle source
# File lib/krpc/connection.rb, line 80 def receive_message(msg_type) msg_length = recv_varint msg_data = recv(msg_length) msg_type.decode(msg_data) end
recv(maxlen = 1)
click to toggle source
# File lib/krpc/connection.rb, line 66 def recv(maxlen = 1) maxlen == 0 ? "" : @socket.read(maxlen) end
recv_varint()
click to toggle source
# File lib/krpc/connection.rb, line 69 def recv_varint int_val = 0 shift = 0 loop do byte = recv.ord int_val |= (byte & 0b0111_1111) << shift return int_val if (byte & 0b1000_0000) == 0 shift += 7 raise(RuntimeError, "too many bytes when decoding varint") if shift >= 64 end end
send(data)
click to toggle source
# File lib/krpc/connection.rb, line 59 def send(data) @socket.send(data, 0) end
send_message(msg)
click to toggle source
# File lib/krpc/connection.rb, line 62 def send_message(msg) send Encoder.encode_message_with_size(msg) end