Over a million developers have joined DZone.

Writing Comet Applications Using JRuby and the Atmosphere Framework

DZone's Guide to

Writing Comet Applications Using JRuby and the Atmosphere Framework

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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:

  require 'java'
  Dir["./Java/atmosphere/atmosphere-spade-server.jar"].each { |jar| require jar }
  include_class 'javax.servlet.http.HttpServlet'
  include_class 'org.atmosphere.cpr.AtmosphereHandler'
  include_class 'org.atmosphere.grizzly.AtmosphereSpadeServer'
  #setup and start the server
  def main
              .addAtmosphereHandler("", ChatPage.new())
                  .addAtmosphereHandler("/chat-stream", ChatStream.new()).start

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

  #serve the chat page
  class ChatPage
    include AtmosphereHandler
    def onEvent(event)
      res = event.getResponse()
      res.addHeader("Cache-Control", "private")
      res.addHeader("Pragma", "no-cache")
      File.open(File.dirname(__FILE__)+'/chat.html').each { |line|

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

  #serve the chat stream and post messages
  class ChatStream
      include AtmosphereHandler
      BEGIN_SCRIPT_TAG = '<script>'
      END_SCRIPT_TAG = '</script>'
      def onEvent(event)
          req = event.getRequest();
          res = event.getResponse();
          res.addHeader("Cache-Control", "private")
          res.addHeader("Pragma", "no-cache")
          if (req.getMethod().upcase === "GET")
              # for IE
              res.getWriter().write("<!-- Comet  enables web " +
                                    "servers to send data without having any need " +
                                    "for the client to request it. -->\n");
          elsif (req.getMethod().upcase === "POST")
              message = req.getParameterValues("message")[0].to_s
              ip = req.getRemoteAddr().to_s
                  BEGIN_SCRIPT_TAG +
                  "window.parent.say('<small>#{ip} - 
                             </small><br><b>#{message}</b>')" +
      def onMessage(event)
          writer = event.getResponse().getWriter()

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!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}