Trick of the Friday #1: Delivering Server Side Events to your Websocket/Comet Application.
When writing asynchronous web application (Comet and/or Websocket based), most of the time you need to generate server sides events from external components or non web-based technology.
As an example, you may have EJBs, JMS queue/topic that may need to deliver server sides events to your set of asynchronous connections. With Atmosphere, it is quite easy to generate server sides events using Broadcaster. A Broadcaster role is to push back server sides events to the Browser. Within the scope of a Web application, all you need to do is:
// Retrieve the default Broadcaster
Broadcaster broadcaster = atmosphereResource.getBroadcaster();
// Or create your own
Broadcaster broadcaster = new Broadcaster(“myBroadcaster”);
// Or let Atmosphere injects it for you like:
public void broadcast(@PathParam(“myBroadcaster”) Broadscaster broadcaster);
This return the Broadcaster associated with the current asynchronous connection (Websocket or Comet). A Broadcaster can be shared amongst all your connections (chat like application) or to a subset based on some topic (pub sub, etc). The Broadcaster concept is really close to an events queue Browser can subscribe to and received asynchronous events.
But what about non web components (EJB, JMS, Akka/Scala Actor, etc.) or web component with different scope (another web application, another Servlet, etc.)? They can also generate server sides events by using Atmosphere’s BroadcasterFactory
Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, “id_of_the_broadcaster”);
Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(JerseyBroadcaster.class, “id_of_the_broadcaster”);
broadcaster.broadcast(‘Hello from an EJB”);
By default, the value of “id_of_the_broadcaster” is based on the Atmosphere’s <url-pattern> value (ex:/*). You can always set that value by calling:
What about if you don’t know the name of your Broadcaster? You can also retrieve all available Broadcasters by doing:
// An unmodifiable collection
Collection<Broadcaster> broadcasters = BroadcasterFactory.getDefault().lookupAll();
In conclusion, being able to generate server sides events from external components is a mandatory features required when writing asynchronous application. Before picking a framework for writing an asynchronous application, always make sure such features is available to avoid having to write it yourself (and maintain it).
For any questions or to download Atmosphere Client and Server Framework, go to our main site and use our Nabble forum (no subscription needed), or follow the team or myself and tweet your questions there! You can also checkout the code on Github. Or download our latest presentation to get an overview of what the framework is.