Created
January 15, 2010 15:12
-
-
Save slayer/278115 to your computer and use it in GitHub Desktop.
This file contains 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
def em_start_websockets(options) | |
options.logger.info "Starting WebSockets daemon on #{options.websocket_host}:#{options.websocket_port} and '#{ENV['RAILS_ENV']}' environment" | |
connections = 0 | |
EventMachine::WebSocket.start(:host => options.websocket_host, :port => options.websocket_port, :debug => false) do |ws| | |
mq = MQ.new | |
user = nil | |
token = nil | |
queue = nil | |
ws.onopen do | |
connections = connections + 1 | |
puts "WebSocket connection open: #{connections}" | |
ws.send( {:message => "hello client #{connections}"}.to_json ) | |
end | |
ws.onclose do | |
puts "Connection closed"; | |
puts " closing queue #{queue}" | |
mq.queue( queue ).unsubscribe | |
connections = connections - 1 | |
end | |
ws.onmessage { |msg| | |
puts "Recieved message: #{msg}" | |
msg = msg.split ' ' | |
case msg[0] | |
when "token" | |
token = msg[1] | |
user = User.find_by_remember_token(token) | |
ws.send( {:message => "hello #{user ? user.email : 'anonymous'}"}.to_json ) | |
when "subscribe" | |
return unless user | |
topic = msg[1] | |
queue = "#{user.email}-#{topic}-#{Time.now.to_i}-#{connections}" | |
puts "creating queue #{queue}" | |
mq.queue( queue, :auto_delete => true ).bind( mq.topic(topic, :auto_delete => true) ).subscribe do |data| | |
data = Marshal.load(data) | |
puts " received data from queue: #{data.to_json}" | |
ws.send data.to_json | |
end | |
when "unsubscribe" | |
return unless user | |
puts " closing queue #{queue}" | |
mq.queue( queue ).unsubscribe | |
end | |
} | |
end |
This file contains 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
ws = new WebSocket("ws://qqqqqqq.com:4000/"); | |
ws.onmessage = function(evt) { console.log(evt.data); }; | |
ws.onclose = function() { console.log("socket closed"); }; | |
ws.onopen = function() { console.log("connected..."); | |
ws.send("token " + $.cookie('remember_token') + "\n"); | |
ws.send("subscribe all" + "\n"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment