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.



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

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

Instance Attribute Details

#hostObject

Returns the value of attribute host.



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

def host
  @host
end

#portObject

Returns the value of attribute port.



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

def port
  @port
end

#sockObject

Returns the value of attribute sock.



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

def sock
  @sock
end

Instance Method Details

#addressObject



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

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

#connectObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fraggle/block/connection.rb', line 19

def connect
 # http://stackoverflow.com/questions/231647/how-do-i-set-the-socket-timeout-in-ruby
 timeout = 10
 addr = Socket.getaddrinfo(@host, nil)
 sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)

 begin
  sock.connect_nonblock(Socket.pack_sockaddr_in(@port, addr[0][3]))
 rescue Errno::EINPROGRESS
  resp = IO.select(nil, [sock], nil, timeout.to_i)
  if resp.nil?
    raise Errno::ECONNREFUSED
  end
  begin
    sock.connect_nonblock(Socket.pack_sockaddr_in(@port, addr[0][3]))
  rescue Errno::EISCONN
  end
 end
 sock
end

#disconnectObject



40
41
42
# File 'lib/fraggle/block/connection.rb', line 40

def disconnect
  @sock.close
end

#readObject



51
52
53
54
55
56
57
58
59
# File 'lib/fraggle/block/connection.rb', line 51

def read
  responses = []
  head = @sock.read(4)
  length = head.unpack("N")[0]
  data = @sock.read(length)
  response = Response.decode(data)
  responses << response if response.valid? 
  responses
end

#send(req) ⇒ Object



44
45
46
47
48
49
# File 'lib/fraggle/block/connection.rb', line 44

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