Skip to content

Understanding AtmosphereResource

jfarcand edited this page May 28, 2012 · 22 revisions

The AtmosphereResource is the central piece of the Atmosphere Framework. An AtmosphereResource represents a remote connection. You can also see an AtmosphereResource as a communication channel between a browser and an application. An application use an AtmosphereResource to handle the life cycle of the connection. For example, to tell the Atmosphere Framework to not close connection and leave it open for later use by calling

    atmosphereResource.suspend();

You can read information about the request and populate the response from an AtmosphereResource. As simple as:

   AtmosphereRequest = atmosphereResource.getRequest();
   AtmosphereResponse = atmosphereResource.getResponse();

If you are familiar with the Servlet technology, AtmosphereRequest/AtmosphereResource can be seen as HttpServletRequest/Response. You can read/write using those objects. You can write messages (or events) using the AtmosphereResponse or directly using the AtmosphereResoure:

  atmosphereResource.write("hello").write("world");

An AtmosphereResource gets delivered to an AtmosphereHanler, and created every time a new connection is made.

An AtmosphereResource is always associated with one or several channel of communication (read Broadcaster). When created, a Broadcaster is always associated with an AtmosphereResource and can be retrieved using

  Broadcaster b = atmosphereResource.getBroadcaster();

You can see a Broadcaster as a "topic" or "channel". You can subscribe to channel, or Broadcaster, by adding an AtmosphereResource to it. You simply do:

  broadcaster.addAtmosphereResource(atmosphereResource);

Once added, messages or events will be delivered to an AtmosphereResource every time Broadcaster#broadcast gets invoked. An AtmosphereResource is associated with an AtmosphereResourceEvent, which always contains the last broadcasted events. You can get it by doing

  Object message = atmosphereResource.getAtmosphereResourceEvent().getMessage();

This allow application to decide to write the event back to the remote client. For example, a remote browser can subscribe to two broadcasters:

 BroadcasterFactory.getDefault().lookup("Java topic").addAtmosphereResource(atmosphereResource);
 BroadcasterFactory.getDefault().lookup("Scala topic").addAtmosphereResource(atmosphereResource);

Now every time a new events or messages get broadcasted, the messages will be send back to the browser for further processing.

You can attach events listeners to an AtmosphereResource and gets notified every time the AtmosphereResource state is about to change.. As simple as

  atmosphereResource.addEventListener(new AtmosphereResourceEventListenerAdapter() ...);

AtmosphereResource are closely tie with AtmosphereHandler.

Clone this wiki locally