Skip to content

Instantly share code, notes, and snippets.

@slayer
Created January 15, 2010 13:48
Show Gist options
  • Save slayer/278070 to your computer and use it in GitHub Desktop.
Save slayer/278070 to your computer and use it in GitHub Desktop.
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|
@user = 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";
@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.email}"}.to_json )
when "subscribe"
mq = MQ.new
@topic = msg[1]
@queue = "#{@user.email}-#{@topic}-#{Time.now.to_i}-#{@connections}"
puts "creating queue #{@queue}"
mq.queue( @queue ).bind( mq.topic(@topic) ).subscribe do |data|
data = Marshal.load(data)
puts " received data from queue: #{data.to_json}"
ws.send data.to_json
end
when "unsubscribe"
puts " unsubscribe..."
end
}
end
end
ws = new WebSocket("ws://qqqqq.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