Class: Gibson::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client

Create a new Gibson::Client instance, the options are passed to Gibson::Connection initialize method.

Examples:

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

Options:

  • :socket - The UNIX socket path, if this option is set a UNIX socket connection will be used. Default: /var/run/gibson.sock

  • :address - The ip address to connect to, if this option is set a TCP socket connection will be used. Default: nil

  • :port - The tcp port to connect to. Default: 10128

  • :timeout - The connection and I/O timeout in milliseconds. Default: 100

  • :keepalive - If a TCP connection will be used, set this to true to use the SO_KEEPALIVE flag on the socket. Default: false



32
33
34
35
# File 'lib/gibson/gibson.rb', line 32

def initialize(opts = {})
  @connection = nil
  @options = opts
end

Instance Method Details

#connectObject

Create the connection.



38
39
40
41
# File 'lib/gibson/gibson.rb', line 38

def connect
  @connection = Connection.new( @options )
  @connection.connect
end

#query(opcode, payload = '') ⇒ Object

Send a query to the server given its opcode and arguments payload. Return the decoded data, or raise one of the RuntimeErrors defined inside Gibson::Protocol.

Raises:

  • (Timeout::Error)


95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/gibson/gibson.rb', line 95

def query( opcode, payload = '' )
  connect if @connection == nil or not @connection.connected?

  psize  = payload.length
  packet = [ 2 + psize, opcode, payload ].pack( 'L<S<Z' + psize.to_s )

  wrote = @connection.write packet

  raise( Timeout::Error, "Couldn't complete writing ( wrote #{wrote} of #{packet.size} bytes )" ) unless packet.size == wrote 
  
  code, encoding, size = @connection.read(7).unpack('S<cL<' )
  data = @connection.read size
  
  raise( Timeout::Error, "Couldn't complete reading ( read #{data.size} of #{size} bytes )" ) unless data.size == size 

  decode code, encoding, size, StringIO.new(data)
end