Class: SimpleIPC::IPC

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

Overview

Socket Class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ IPC

Default initialization hash is:

{:port => 5000,      # Port to listen at
 :host => LOCALHOST, # Host to talk to
 :timeout => 0,      # Timeout for blocking connections
 :blocking => false} # use blocking read

Parameters:

  • args (Hash) (defaults to: {})

    a hash of config values

Raises:

  • (ArgumentError)


128
129
130
131
132
133
# File 'lib/simple_ipc.rb', line 128

def initialize(args = {})
  raise ArgumentError, "expecting an Hash" unless args.kind_of? Hash
  @cfg = {:port => 5000, :host => LOCALHOST, :timeout => 0}
  @cfg.merge! args
  @socket = Socket.new @cfg
end

Instance Attribute Details

#cfgObject

Returns the value of attribute cfg.



120
121
122
# File 'lib/simple_ipc.rb', line 120

def cfg
  @cfg
end

Instance Method Details

#closeObject

Closes the socket.



187
188
189
# File 'lib/simple_ipc.rb', line 187

def close
  @socket.close
end

#get {|String| ... } ⇒ Object

Gets an object (only valid if it is a server). An optional block can be given for parsing the received String. If no block is given, then the YAML#load deserialization is automatically used.

Yields:

  • (String)

    a block that deserializes the received String

Returns:

  • (Object)

    a parsed object



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/simple_ipc.rb', line 163

def get
  result = nil
  begin
    if @cfg[:timeout] > 0 and !@cfg[:nonblock] then
      Timeout::timeout(@cfg[:timeout]) do |to|
        result = get_
      end
    else 
      result = get_
    end
  rescue Timeout::Error
    result = nil
  rescue Errno::EAGAIN
    return nil
  end

  if block_given? then
    return yield(result)
  else
    return YAML.load(result)
  end
end

#listenObject

Puts the object in listening state (becomes a server).



154
155
156
# File 'lib/simple_ipc.rb', line 154

def listen
  @socket.listen
end

#send(something) {|Object| ... } ⇒ Object

Sends a general object to the server. If an optional block is given, then it is used to perform the object serialization. Otherwise, YAML#dump is used for serialization.

Parameters:

  • something (Object)

    an object

Yields:

  • (Object)

    a block that serializes the received Object



140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/simple_ipc.rb', line 140

def send(something)
  if block_given? then
    payload = yield(something)
  else
    payload = YAML.dump(something)
  end
  length = [payload.size].pack(LENGTH_CODE)
  @socket.connect
  @socket.print length
  @socket.print payload
  return payload
end