require 'nanomsg' port = 60000 socks = [] m = 1 m.times { |i| socks << NanoMsg::PairSocket.new addr = "tcp://127.0.0.1:#{port}" socks.last.bind addr puts "listening on #{addr}" port += 1 } threads = [] socks.each_with_index { |n,i| threads << Thread.new { puts "sending hello to #{i}" n.send "hello #{i}" sleep 1 n.recv puts "got hello from #{i}" } } threads.each { |thr| thr.join } threads.clear socks.each_with_index {|n,i| threads << Thread.new { while true msg = n.recv puts "message from #{i}: #{msg}" break if msg == "shutting down" sleep 1 end } } i = 0 j = 0 while line = STDIN.gets puts "sending source #{i} to #{j}" socks[j].send "#{j} #{i} #{line.strip}" sleep 1 i += 1 j += 1 j = 0 if j==m end socks.each { |n| Thread.new { n.send "shutdown" } } threads.each { |thr| thr.join }