Home > Uncategorized > Writing Comet Applications Using JRuby and the Atmosphere Framework

Writing Comet Applications Using JRuby and the Atmosphere Framework

Writing Atmosphere’s Comet based applications is simple. Imagine using JRuby instead of Java…it becomes really simple!. As with Scala, it is also possible to write Comet application with Atmosphere Framework using JRuby.


A user of Atmosphere recently posted the famous chat application written using JRuby and an embedded instance of Jetty. I’ve decided to write the same application using the Atmosphere Spade Server, which build on top of Jersey and Grizzly (will soon support Netty and Jetty). The idea behind the Atmosphere Spade Server is to make it really simple to test and embed your Comet application. Note that any application written using the Atmosphere Spade Server is portable, e.g. it will also deploy into any Servlet Container like Tomcat, Glassfish, Weblogic etc.

Before jumping into JRuby, let’s just explore the Atmosphere Spade Server main class, AtmosphereSpadeServer:

public static AtmosphereSpadeServer.build(String uri);

Invoking that simple method will automatically creates, under the hood, a Grizzly Servlet Container instance ready to receive requests based on the URI entered


Next step is to add your Atmosphere POJO aka AtmosphereHandler (I recommend you read that post for more details about AtmosphereHandler):


And finally, you are ready to start it:


If you are using Atmosphere Core/REST (powered by Jersey), it event simpler as you don’t need to define AtmosphereHandler, but instead just tell Jersey the name of the package to look for JAX RS resources:

AtmosphereSpadeServer build("http://localhost:8080/","org.atmosphere.myresources").start()

Now let’s jump into JRuby world and uses the AtmosphereSpadeServer:

  1 require 'java'
  3 Dir["./Java/atmosphere/atmosphere-spade-server.jar"].each { |jar| require jar }
  5 include_class 'javax.servlet.http.HttpServlet'
  6 include_class 'org.atmosphere.cpr.AtmosphereHandler'
  7 include_class 'org.atmosphere.grizzly.AtmosphereSpadeServer'
  9 #setup and start the server
 10 def main
 11   AtmosphereSpadeServer.build("http://localhost:8080/")
 12             .addAtmosphereHandler("", ChatPage.new())
 13                 .addAtmosphereHandler("/chat-stream", ChatStream.new()).start
 14 end

The above code starts the server using two AtmosphereHandler. The first will send back a chat.html page to be rendered by the browser

 17 #serve the chat page
 18 class ChatPage
 19   include AtmosphereHandler
 21   def onEvent(event)
 22     Kernel.load(__FILE__)
 23     res = event.getResponse()
 25     res.setContentType("text/html")
 26     res.addHeader("Cache-Control", "private")
 27     res.addHeader("Pragma", "no-cache")
 28     File.open(File.dirname(__FILE__)+'/chat.html').each { |line|
 29       res.getWriter().write(line)
 30     }
 31     res.getWriter().flush()
 32     event
 33   end
 34 end

The second one is used for suspending the response and broadcasting chat messages

 36 #serve the chat stream and post messages
 37 class ChatStream
 38     include AtmosphereHandler
 40     BEGIN_SCRIPT_TAG = '<script>'
 41     END_SCRIPT_TAG = '</script>'
 43     def onEvent(event)
 44         req = event.getRequest();
 45         res = event.getResponse();
 47         res.setContentType("text/html")
 48         res.addHeader("Cache-Control", "private")
 49         res.addHeader("Pragma", "no-cache")
 50         res.setCharacterEncoding("UTF-8");
 52         if (req.getMethod().upcase === "GET")
 53             # for IE
 54             res.getWriter().write("<!-- Comet  enables web " +
 55                                   "servers to send data without having any need " +
 56                                   "for the client to request it. -->\n");
 57             res.getWriter().flush();
 58             event.suspend();
 60         elsif (req.getMethod().upcase === "POST")
 61             message = req.getParameterValues("message")[0].to_s
 62             ip = req.getRemoteAddr().to_s
 63             event.getBroadcaster().broadcast(
 64                 BEGIN_SCRIPT_TAG +
 65                 "window.parent.say('<small>#{ip} - 
                             </small><br><b>#{message}</b>')" +
 66                 END_SCRIPT_TAG);
 68                 res.getWriter().write('success')
 69                 res.getWriter().flush();
 70         end     
 72         event
 73     end 
 75     def onMessage(event)
 76         writer = event.getResponse().getWriter()
 77         writer.write(event.getMessage().to_s.ljust(1*1024))
 78         writer.flush()
 79         event
 80     end 
 81 end

With Atmosphere, every suspended connection are represented by an instance of AtmosphereEvent, and when a Broadcast operations happens, the AtmosphereHandler.onMessage(AtmosphereEvent) will be invoked hence an application can write back the broadcasted message.

Of course, you can do much more complex application using Atmosphere and JRuby, but my goal here was just to show how easy it can be.

For any questions or to download the above sample, go to our main site and use our Nabble forum (no subscription needed) or follow us on Twitter and tweet your questions there!

var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.&#8221; : “http://www.&#8221;);
document.write(unescape(“%3Cscript src='” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

var pageTracker = _gat._getTracker(“UA-3111670-3”);


Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: