Commit bb9fd9e

mo khan <mo@mokhan.ca>
2014-10-10 19:59:20
create a chat client.
1 parent 3e27219
Changed files (2)
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
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