summaryrefslogtreecommitdiff
path: root/nanomsg/master.rb
blob: e21f88d640163cfcb7b901e6ae90940b95510be6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 }