Browse files

Merge pull request #302 from devin-c/ruby_asyncsrv

Add ruby asynchronous client-to-server example
  • Loading branch information...
2 parents 17a3aeb + 68592a6 commit cf2a37ae66cb432b243f9a85161ac6911debff8a @hintjens hintjens committed Mar 9, 2013
Showing with 69 additions and 0 deletions.
  1. +69 −0 examples/Ruby/asyncsrv.rb
View
69 examples/Ruby/asyncsrv.rb
@@ -0,0 +1,69 @@
+# Asynchronous client-to-server (DEALER to ROUTER)
+
+require 'rubygems'
+require 'ffi-rzmq'
+
+def client
+ context = ZMQ::Context.new
+ client = context.socket ZMQ::DEALER
+ client.identity = "%04X-%04X" % [rand(0x10000), rand(0x10000)]
+ client.connect "ipc://frontend.ipc"
+
+ poller = ZMQ::Poller.new
+ poller.register_readable(client)
+
+ request_number = 0
+
+ loop do
+
+ 100.times do |tick|
+ if poller.poll(10) == 1
+ client.recv_strings message = []
+ puts "#{client.identity}: #{message.last}"
+ end
+ end
+
+ client.send_string "Req ##{request_number += 1}"
+ end
+
+ client.close
+ context.destroy
+end
+
+def worker(context)
+ worker = context.socket ZMQ::DEALER
+ worker.connect "inproc://backend"
+
+ loop do
+ worker.recv_strings message = []
+
+ rand(0..4).times do
+ sleep rand
+ worker.send_strings message
+ end
+ end
+
+ worker.close
+end
+
+def server
+ context = ZMQ::Context.new
+ frontend = context.socket ZMQ::ROUTER
+ backend = context.socket ZMQ::DEALER
+
+ frontend.bind "ipc://frontend.ipc"
+ backend.bind "inproc://backend"
+
+ poller = ZMQ::Poller.new
+ poller.register_readable frontend
+ poller.register_readable backend
+
+ 5.times { Thread.new { worker context } }
+
+ ZMQ::Device.create ZMQ::QUEUE, frontend, backend
+
+end
+
+3.times { Thread.new { client } }
+
+server

0 comments on commit cf2a37a

Please sign in to comment.