Last active
December 30, 2015 20:18
-
-
Save dmitriy-sqrt/7879328 to your computer and use it in GitHub Desktop.
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
| require 'amqp' | |
| require 'em-websocket' | |
| class Websockets | |
| def self.publisher(message = "Hello world!"+Time.now.to_s, routing_key = "amqp.test") #routing_key will contain current_user.id | |
| #connect to rabbitmq service, open channel, create queue | |
| AMQP.start("amqp://localhost") do |connection| # connection is open and ready to be used | |
| channel = AMQP::Channel.new(connection) | |
| exchange = channel.direct("") | |
| #publish a message | |
| puts "Send: #{message}" | |
| exchange.publish message, :routing_key => routing_key #each client should have his queue name | |
| # stop in 2 seconds | |
| EventMachine.add_timer(2.0) { connection.close { EventMachine.stop } } | |
| end | |
| end | |
| def self.consumer() #but where the hell can i take user_id here? | |
| EventMachine.run do | |
| EventMachine::WebSocket.start(:host => '127.0.0.1', :port => 8030) do |ws| | |
| ws.onopen { | |
| puts "WS connection opened" | |
| AMQP.connect(:host => '127.0.0.1') do |connection| | |
| puts "amqp connect" | |
| channel = AMQP::Channel.new(connection) | |
| exchange = channel.direct("") | |
| #subscribe to rabbitmq queue | |
| channel.queue("amqp.test", :auto_delete => true).subscribe do |payload| | |
| puts "AMQP: Received a message: '#{payload}', resending it to websocket..." | |
| ws.send "#{payload}" | |
| end | |
| end | |
| } | |
| ws.onclose { puts "Connection closed" } | |
| ws.onmessage { |msg| } | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment