lib/pigato/client.rb in pigato-0.1.0 vs lib/pigato/client.rb in pigato-0.1.1
- old
+ new
@@ -1,71 +1,64 @@
-module Pigato
- class Client
- include MDP
+require "json"
+require "ffi-rzmq"
- attr_accessor :timeout
+class PigatoClient
- def initialize broker
- @broker = broker
- @context = ZMQ::Context.new(1)
- @client = nil
- @poller = ZMQ::Poller.new
- @timeout = 2500
+ def initialize broker
+ @broker = broker
+ @context = ZMQ::Context.new(1)
+ @client = nil
+ @poller = ZMQ::Poller.new
- reconnect_to_broker
- end
+ reconnect_to_broker
+ end
- def send service, request, timeout = 2500
- request = [request.to_json]
+ def send service, request, timeout = 2500
+ request = [request.to_json]
- rid = 'RID' + (rand() * 1000000).to_s
- # Prefix request with protocol frames
- # Frame 0: empty (REQ emulation)
- # Frame 1: "MDPCxy" (six bytes, MDP/Client x.y)
- # Frame 2: Service name (printable string)
- request = [MDP::C_CLIENT, MDP::W_REQUEST, service, rid].concat(request)
- @client.send_strings request
+ rid = 'RID' + (rand() * 1000000).to_s
+ request = [Pigato::C_CLIENT, Pigato::W_REQUEST, service, rid].concat(request)
+ @client.send_strings request
- res = Array.new
- res << rid
+ res = Array.new
+ res << rid
- data = Array.new
- while 1 do
- chunk = _recv(timeout)
- data << chunk[4]
- break if chunk[0] == MDP::W_REPLY
- end
-
- res << data
- res
+ data = Array.new
+ while 1 do
+ chunk = _recv(timeout)
+ data << chunk[4]
+ break if chunk[0] == Pigato::W_REPLY
end
- def _recv timeout
- items = @poller.poll(timeout)
- if items
- messages = []
- @client.recv_strings messages
+ res << data
+ res
+ end
- # header
- if messages.shift != MDP::C_CLIENT
- raise RuntimeError, "Not a valid MDP message"
- end
+ def _recv timeout
+ items = @poller.poll(timeout)
+ if items
+ messages = []
+ @client.recv_strings messages
- return messages
+ # header
+ if messages.shift != Pigato::C_CLIENT
+ raise RuntimeError, "Not a valid Pigato message"
end
- nil
+ return messages
end
- def reconnect_to_broker
- if @client
- @poller.deregister @client, ZMQ::DEALER
- end
+ nil
+ end
- @client = @context.socket ZMQ::DEALER
- @client.setsockopt ZMQ::LINGER, 0
- @client.setsockopt ZMQ::IDENTITY, "C" + (rand() * 10).to_s
- @client.connect @broker
- @poller.register @client, ZMQ::POLLIN
+ def reconnect_to_broker
+ if @client
+ @poller.deregister @client, ZMQ::DEALER
end
+
+ @client = @context.socket ZMQ::DEALER
+ @client.setsockopt ZMQ::LINGER, 0
+ @client.setsockopt ZMQ::IDENTITY, "C" + (rand() * 10).to_s
+ @client.connect @broker
+ @poller.register @client, ZMQ::POLLIN
end
end