Class: Fraggle::Block::Connection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Connection

Returns a new instance of Connection.



10
11
12
13
14
# File 'lib/fraggle/block/connection.rb', line 10

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

Instance Attribute Details

#hostObject

Returns the value of attribute host.



8
9
10
# File 'lib/fraggle/block/connection.rb', line 8

def host
  @host
end

#portObject

Returns the value of attribute port.



8
9
10
# File 'lib/fraggle/block/connection.rb', line 8

def port
  @port
end

#sockObject

Returns the value of attribute sock.



8
9
10
# File 'lib/fraggle/block/connection.rb', line 8

def sock
  @sock
end

Instance Method Details

#addressObject



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

def address
  "#{@host}:#{@port}"
end

#connectObject



20
21
22
23
24
25
26
# File 'lib/fraggle/block/connection.rb', line 20

def connect
  Timeout::timeout(10) do
    s = TCPSocket.new(@host, @port)
    s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
    s
  end
end

#disconnectObject



28
29
30
# File 'lib/fraggle/block/connection.rb', line 28

def disconnect
  @sock.close
end

#readObject

Raises:

  • (Errno::ECONNRESET)


39
40
41
42
43
44
45
46
# File 'lib/fraggle/block/connection.rb', line 39

def read
  head = @sock.read(4)
  raise(Errno::ECONNRESET) if !head
  length = head.unpack("N")[0]
  data = @sock.read(length)
  raise(Errno::ECONNRESET) if !data
  Response.decode(data)
end

#send(req) ⇒ Object



32
33
34
35
36
37
# File 'lib/fraggle/block/connection.rb', line 32

def send(req)
  req.tag = 0
  data = req.encode
  head = [data.length].pack("N")
  @sock.write(head+data)
end