Last active
August 29, 2015 13:59
-
-
Save compleatang/10582842 to your computer and use it in GitHub Desktop.
ZMQ Lazy Pirate Pattern in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # Author: Han Holl <[email protected]> | |
| require 'rubygems' | |
| require 'ffi-rzmq' | |
| class LPClient | |
| def initialize(connect, retries = nil, timeout = nil) | |
| @connect = connect | |
| @retries = (retries || 3).to_i | |
| @timeout = (timeout || 10).to_i | |
| @ctx = ZMQ::Context.new(1) | |
| client_sock | |
| at_exit do | |
| @socket.close | |
| end | |
| end | |
| def client_sock | |
| @socket = @ctx.socket(ZMQ::REQ) | |
| @socket.setsockopt(ZMQ::LINGER, 0) | |
| @socket.connect(@connect) | |
| end | |
| def send(message) | |
| @retries.times do |tries| | |
| raise("Send: #{message} failed") unless @socket.send(message) | |
| if ZMQ.select( [@socket], nil, nil, @timeout) | |
| yield @socket.recv | |
| return | |
| else | |
| @socket.close | |
| client_sock | |
| end | |
| end | |
| raise 'Server down' | |
| end | |
| end | |
| if $0 == __FILE__ | |
| server = LPClient.new(ARGV[0] || "tcp://localhost:5555", ARGV[1], ARGV[2]) | |
| count = 0 | |
| loop do | |
| request = "#{count}" | |
| count += 1 | |
| server.send(request) do |reply| | |
| if reply == request | |
| puts("I: server replied OK (#{reply})") | |
| else | |
| puts("E: malformed reply from server: #{reply}") | |
| end | |
| end | |
| end | |
| puts 'success' | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # Author: Han Holl <[email protected]> | |
| require 'rubygems' | |
| require 'zmq' | |
| class LPServer | |
| def initialize(connect) | |
| @ctx = ZMQ::Context.new(1) | |
| @socket = @ctx.socket(ZMQ::REP) | |
| @socket.bind(connect) | |
| end | |
| def run | |
| begin | |
| loop do | |
| rsl = yield @socket.recv | |
| @socket.send rsl | |
| end | |
| ensure | |
| @socket.close | |
| @ctx.close | |
| end | |
| end | |
| end | |
| if $0 == __FILE__ | |
| cycles = 0 | |
| srand | |
| LPServer.new(ARGV[0] || "tcp://*:5555").run do |request| | |
| cycles += 1 | |
| if cycles > 3 | |
| if rand(3) == 0 | |
| puts "I: simulating a crash" | |
| break | |
| elsif rand(3) == 0 | |
| puts "I: simulating CPU overload" | |
| sleep(3) | |
| end | |
| end | |
| puts "I: normal request (#{request})" | |
| sleep(1) | |
| request | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment