Class: KRPC::Connection

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

Overview

A TCP Connection.

Direct Known Subclasses

RPCConnection, StreamConnection

Constant Summary collapse

DEFAULT_SERVER_HOST =
"127.0.0.1"
DEFAULT_SERVER_RPC_PORT =
50000
DEFAULT_SERVER_STREAM_PORT =
50001

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Connection

Returns a new instance of Connection.



16
17
18
# File 'lib/krpc/connection.rb', line 16

def initialize(host, port)
  @host, @port = host, port
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



14
15
16
# File 'lib/krpc/connection.rb', line 14

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



14
15
16
# File 'lib/krpc/connection.rb', line 14

def port
  @port
end

#socketObject (readonly)

Returns the value of attribute socket.



14
15
16
# File 'lib/krpc/connection.rb', line 14

def socket
  @socket
end

Instance Method Details

#cleanupObject



50
# File 'lib/krpc/connection.rb', line 50

def cleanup; end

#closeObject

Close connection and clean up.



36
37
38
39
40
41
42
# File 'lib/krpc/connection.rb', line 36

def close
  if connected?
    socket.close
    cleanup
    true
  else false end
end

#connectObject

Connect and perform handshake.



21
22
23
24
25
26
27
28
29
30
31
32
33
# 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?Boolean

Return ‘true` if connected to a server, `false` otherwise.

Returns:



45
46
47
# File 'lib/krpc/connection.rb', line 45

def connected?
  !socket.nil? && !socket.closed?
end

#handshakeObject



49
# File 'lib/krpc/connection.rb', line 49

def handshake; end

#recv(maxlen = 1) ⇒ Object



53
54
55
# File 'lib/krpc/connection.rb', line 53

def recv(maxlen = 1)
  maxlen == 0 ? "" : @socket.read(maxlen)
end

#recv_varintObject



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/krpc/connection.rb', line 57

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(msg) ⇒ Object



52
# File 'lib/krpc/connection.rb', line 52

def send(msg) @socket.send(msg, 0) end