lib/pigato/client.rb in pigato-0.1.3 vs lib/pigato/client.rb in pigato-0.1.5
- old
+ new
@@ -1,54 +1,57 @@
-require "json"
-require "ffi-rzmq"
+require "oj"
require "securerandom"
class PigatoClient
def initialize broker
@broker = broker
@context = ZMQ::Context.new(1)
@client = nil
@poller = ZMQ::Poller.new
+ @timeout = 2500
reconnect_to_broker
end
- def send service, request, timeout = 2500
- request = [request.to_json]
+ def send service, request, timeout = @timeout
+ request = [Oj.dump(request)]
rid = SecureRandom.uuid
request = [Pigato::C_CLIENT, Pigato::W_REQUEST, service, rid].concat(request)
@client.send_strings request
- res = Array.new
- res << rid
-
- data = Array.new
+ res = []
while 1 do
- chunk = _recv(timeout)
- data << chunk[4]
+ chunk = _recv(rid, timeout)
+ break if chunk == nil
+ res << Oj.load(chunk[4])
break if chunk[0] == Pigato::W_REPLY
end
- res << data
res
end
- def _recv timeout
+ def _recv rid, timeout = @timeout
items = @poller.poll(timeout)
- if items
- messages = []
- @client.recv_strings messages
+ if items
+ msg = []
+ d1 = Time.now
+ while 1 do
+ @client.recv_strings(msg, ZMQ::DONTWAIT)
+ msg = [] if msg.length < 5 || msg[3] != rid
+ break if msg.length > 0 || ((Time.now - d1) * 1000 > timeout)
+ end
+ return nil if msg.length == 0
+
# header
- if messages.shift != Pigato::C_CLIENT
+ if msg.shift != Pigato::C_CLIENT
raise RuntimeError, "Not a valid Pigato message"
end
- return messages
+ return msg
end
-
nil
end
def reconnect_to_broker
if @client