summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2014-10-10 13:59:20 -0600
committermo khan <mo@mokhan.ca>2014-10-10 13:59:20 -0600
commitbb9fd9eb612d80d639aa526a8881612cd355c015 (patch)
tree1e5fa35a5911191b5d970b6fb74f580f1154bea4
parent3e27219f6009e76b9e22c1731c9e09f51d74c3ad (diff)
create a chat client.
-rw-r--r--lib/6-chit-chat/publish.rb17
-rw-r--r--lib/6-chit-chat/subscribe.rb32
2 files changed, 49 insertions, 0 deletions
diff --git a/lib/6-chit-chat/publish.rb b/lib/6-chit-chat/publish.rb
new file mode 100644
index 0000000..0179dce
--- /dev/null
+++ b/lib/6-chit-chat/publish.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+## encoding: utf-8
+
+require "bunny"
+
+connection = Bunny.new
+connection.start
+
+channel = connection.create_channel
+exchange = channel.topic("chitchat")
+username = `'whoami'`.chomp!
+message = ARGV.empty? ? "Hi!" : ARGV.join(" ")
+
+exchange.publish(message, routing_key: username)
+puts " [x] Sent #{username}:#{message}"
+
+connection.close
diff --git a/lib/6-chit-chat/subscribe.rb b/lib/6-chit-chat/subscribe.rb
new file mode 100644
index 0000000..121de32
--- /dev/null
+++ b/lib/6-chit-chat/subscribe.rb
@@ -0,0 +1,32 @@
+#!/usr/bin/env ruby
+## encoding: utf-8
+
+require "bunny"
+
+if ARGV.empty?
+ ARGV.push('#')
+end
+
+connection = Bunny.new
+connection.start
+
+channel = connection.create_channel
+exchange = channel.topic("chitchat")
+queue = channel.queue("", exclusive: true)
+
+ARGV.each do |username|
+ queue.bind(exchange, routing_key: username)
+end
+
+puts " [*] Waiting for gossip. To exit press CTRL+C"
+
+begin
+ queue.subscribe(block: true) do |delivery_info, properties, body|
+ puts " [x] #{delivery_info.routing_key}:#{body}"
+ message = "#{delivery_info.routing_key} says #{body}"
+ system("say '#{message}'")
+ end
+rescue Interrupt => _
+ channel.close
+ connection.close
+end