Search code examples
atmosphere

Broadcasting in Atmosphere, which class to extend?


I'm using the atmosphere framework and I'm running a thread started in a ServletContextListener.

I would like to broadcast data that this thread puts in the context however I'm confused what class I would have to extend where I can implement ServletContextAttributeListener.

I'm currently extending the OnMessage class but that doesn't seem adequate.

public class SerialComInit implements ServletContextListener {
        //..
        private static final String SHUTDOWN_REQ = "SHUTDOWN";
        public void attributeAdded(ServletContextAttributeEvent event) {

            queue = (BlockingQueue<String>) event.getServletContext().getAttribute("serialPortData");

            //TODO Use jackson to generate JSON
            //TODO Implement SHUTDOWN command on server side
            //we always get a null here on first try that's why I added null check
            if (queue == null){
                System.out.println("Queue is empty");
            } else {
                String item;
                try {
                    //blocks while queue is empty
                    while ((item = queue.take()) != SHUTDOWN_REQ) {
                        System.out.println("*******WEB*******"+item+"*******");
                        //TODO Broadcast message to connected clients
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("queue error");
                    //e.printStackTrace();
                }
            }       
        }
   //..
}

Solution

  • I solved my problem by extending the AbstractReflectorAtmosphereHandler.

    In my ServletContextAttributeListener -> attributeAdded call it used

    MetaBroadcaster.getDefault().broadcastTo("/", "message");