class Gibson::Connection

Constants

DEFAULTS

Connection default options.

Public Class Methods

new(opts = {}) click to toggle source

Create a new Connection instance with custom options. If no options are specified, Connection.DEFAULTS will be used. For instance:

Gibson::Client.new                         # will create a connection to the default /var/run/gibson.sock UNIX socket.
Gibson::Client.new :address => '127.0.0.1' # will connect to localhost:10128
# File lib/gibson/connection.rb, line 27
def initialize(opts = {})
  @sock = nil
  @connected = false
  @options = DEFAULTS.merge(opts)
end

Public Instance Methods

close() click to toggle source

Close the connection.

# File lib/gibson/connection.rb, line 58
def close
  @sock.close if connected?
end
connect() click to toggle source

Attempt a connection with the specified options until @options is reached.

# File lib/gibson/connection.rb, line 42
def connect
  Timeout.timeout(@options[:timeout]) do
    if @options[:address] != nil
      @sock = TCPSocket.new( @options[:address], @options[:port] ) 
      @sock.setsockopt( Socket::IPPROTO_TCP, Socket::TCP_NODELAY, true )
      @sock.setsockopt( Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true ) if @options[:keepalive]
    else
      @sock = UNIXSocket.open( @options[:socket] )
    end

    @connected = true
  end
end
connected?() click to toggle source

Return true if connection is enstablished, otherwise false.

# File lib/gibson/connection.rb, line 35
def connected?
  @connected
end
read(n) click to toggle source

Read specified amount of data from the socket.

# File lib/gibson/connection.rb, line 83
def read(n)
  read = 0
  data = ""

  while read < n do
    wait_readable

    left = n - read
    
    data += @sock.recv left
    read = data.size
  end

  data
end
wait_readable() click to toggle source

Wait for the socket to be in a readable state for @options milliseconds.

# File lib/gibson/connection.rb, line 70
def wait_readable
  IO.select( [@sock], nil, nil, @options[:timeout] ) || raise(Timeout::Error, "IO timeout")
end
wait_writable() click to toggle source

Wait for the socket to be in a writable state for @options milliseconds.

# File lib/gibson/connection.rb, line 64
def wait_writable
  IO.select(nil, [@sock], nil, @options[:timeout] ) || raise(Timeout::Error, "IO timeout")
end
write(data) click to toggle source

Write data to the socket.

# File lib/gibson/connection.rb, line 76
def write(data)
  wait_writable
  @sock.write data
end