Kaazing WebSocket Gateway

Orange guy with box of questions

Creating a Stomp-Driven Application in Adobe Flex

Technologies used: Adobe Flex, Stomp, Kaazing WebSocket Gateway, and Apache ActiveMQ

This document contains the following sections:

Introduction

There are several innovations within the HTML 5 specification that will forever change the direction of the Web. Two of these innovations in particular--Web sockets and Server-sent events--revolutionize the way Web applications are going to be architected, developed, and deployed. Until recently, bi‑directional browser communication has been an elusive goal of the Web community. However, with updates to the HTML 5 specification, developers can now use a full-duplex communications channel that operates over a single socket.

HTML 5's WebSocket interface enables communication from the browser to any TCP-based back-end service (for example, JMS, JMX, IMAP, and Jabber). For example, it is now possible to avoid convoluted architectures by simply channeling certain protocols to the browser over HTTP and Web applications can now be deployed without the need for a traditional Web application server.

Kaazing WebSocket Gateway delivers an enterprise WebSocket server that enables full-duplex communication from the browser to any TCP-based back-end service. Kaazing WebSocket Gateway is the first enterprise solution that understands the WebSocket protocol and enables direct communication with all major enterprise protocols (for example, Stomp, JMS, IMAP, JDBC, and Jabber).

Kaazing WebSocket Gateway eliminates the need for using convoluted server- and client-side architectures to map server-side protocols to the browser over HTTP. Web developers can use the Flash plugin's support for ActionScript and code directly against the back-end services without the need for custom Servlets or server-side programming.

Overview of Stomp

Stomp (Streaming Text Oriented Messaging Protocol) is a simple, yet effective protocol. It provides an interoperable wire format that allows Stomp clients to communicate with almost every available message broker. An example of a message broker that provides built-in support for Stomp is Apache ActiveMQ. The Stomp protocol offers the following commands:

  • ABORT
  • ACK
  • BEGIN
  • COMMIT
  • CONNECT
  • DISCONNECT
  • SEND
  • SUBSCRIBE
  • UNSUBSCRIBE

In this tutorial you use Apache ActiveMQ as the messaging system and Stomp as the communication protocol. Refer to the Stomp Protocol Specification for more information about Stomp and the Stomp commands.

One important Stomp concept--the frame--deserves a little bit more explanation. A frame encapsulates the message payload. The following is an example of a Stomp CONNECT frame, which is used by the client to establish a connection to a back-end system:

CONNECT\n
login: <username>\n
passcode:<passcode>\n
\n
^@

Note: In this example, \n represents the newline character and ^@ represents the null character.

As shown in the example, the frame starts with a Stomp command (CONNECT, in this case), followed by a newline character. Next are the headers in <key>:<value> pairs followed by newline characters. A blank line indicates the end of the headers and the beginning of the message body and the null character indicates the end of the frame.

Overview of Apache ActiveMQ

Apache ActiveMQ is an open source message broker and Java Message Service (JMS) provider developed, distributed, and licensed by the Apache Foundation. Apache ActiveMQ provides a publish-subscribe model based on the JMS specification. It is a highly viable, light-weight solution for both queue-based peer-to-peer messaging and topic-based publish-subscribe communication. Apache ActiveMQ comes with built-in support for the Stomp protocol that is used in this tutorial. Refer to http://activemq.apache.org for more information about Apache ActiveMQ.

Note: For this tutorial, It is also possible to use another Stomp-compliant server, such as RabbitMQ with the rabbitmq-stomp adapter (see http://www.rabbitmq.com). By default, Kaazing Gateway is configured to connect to the Stomp-compliant server on port 61613. You can configure the Stomp proxy's connect URL in the file KAAZING_HOME/conf/gateway-config.xml.

WebSocket and Stomp

WebSocket enables direct communication from the browser to a Stomp broker. Kaazing Gateway provides the StompClient client library, which radically simplifies the application design and eliminates the need for using convoluted server- and client-side architectures to map server-side protocols to the browser over HTTP. Web developers can use ActionScript and code directly against the back-end services without the need for custom Servlets or server-side programming.

Using the StompClient ActionScript client library, you can take advantage of many Stomp features, making Adobe Flex a first-class citizen in Stomp JMS applications. Since the implementation is layered on top of ByteSocket, which uses WebSocket--and thus the entire stack of Kaazing HTML 5 Communications client libraries--applications developed using the StompClient ActionScript library are provided with guaranteed persistence, reliability, and message-receipt acknowledgment all the way to the browser.

Creating a Stomp-Driven Application in Adobe Flex

Before getting started, take a look at what you are trying to build. This Web application contains the following sections:

  1. Connect and disconnect
  2. Subscribe and unsubscribe
  3. Begin, commit, and abort a transaction
  4. Message window

The following figure shows the completed Stomp-driven Web application.

Flex Stomp client

Setting Up the Development Environment

Before you start building the Stomp-driven application, you must download, install, and run the Kaazing WebSocket Gateway demo bundle and some additional software.

Kaazing WebSocket Gateway

Download, install, and run Kaazing WebSocket Gateway by performing the following steps. Refer to Getting Started for more information.

Adobe Flex SDK

You also need the Adobe Flex 3 Software Development Kit (SDK) for this tutorial. You use the Adobe Flex 3 SDK to compile the created ActionScript file to produce a SWF file - which is the target application. You can download the Adobe Flex 3 SDK from the Adobe download site and install it into your local drive.

Starter Files

Starter files are located in the KAAZING_HOME/web/tutorials/stomp-actionscript directory of Kaazing Gateway demo bundle. These files provide a starting point to avoid having to build everything from scratch.

Creating the Stomp-Driven Application

  1. Navigate to KAAZING_HOME/web/tutorials/stomp-actionscript/.
  2. Open the stomp.mxml file in your preferred editor. stomp.mxml is an ActionScript file with a user interface (UI) template for the demo that contains preconfigured code for logging messages. It contains a few TODO sections and that is where you add ActionScript code to build the client using the Kaazing Stomp protocol library for Adobe Flex. The ActionScript code represents various regions in the application UI and has IDs for buttons to simplify attaching handlers.
  3. Once you have familiarized yourself with the stomp.mxml file, you can start adding the missing pieces. First, import the Kaazing StompClient library, defined in the Adobe Flex client library (the SWC file located in the tutorial directory, also available in KAAZING_HOME/lib/client/flex) that allows you to open a socket and fully leverage bi-directional binary communication for all browsers. The Adobe Flex client library auto-detects any native browser support for WebSocket and Server-sent events (SSE). If the flash plug-in does not support WebSocket and SSE the library automatically falls back to Kaazing's client-side emulation.
    Replace:

    //TODO1: import required libraries

    With:

    import com.kaazing.gateway.client.protocol.StompClient;
    private var client:StompClient;

  4. Next, in the initApp() method, you create an instance of the StompClient ActionScript object and associate callback methods to receive callbacks on events
    Replace:

    //TODO2: create the Stomp client and associate handlers

    in the initApp() method with:

    client = new StompClient()

    //set handlers
    client.onopen = openHandler
    client.onmessage = readHandler
    client.onclose = closedHandler
    client.onerror = errorHandler

  5. Next, add methods referenced earlier to stomp.mxml after the initApp()method. This implementation calls the log() function (already implemented in the starter file).

    private function openHandler(headers:Object):void {
      log("CONNECTION OPENED\n")
    }

    private function closedHandler():void {
      log("\nCONNECTION CLOSED")
    }

    private function readHandler(headers:Object, body:*):void {
      log("\nMESSAGE: "+body+"\n")
    }

    private function errorHandler(headers:Object, body:String):void {
      log("ERROR")
      log(String(headers))
      log(body)
    }

    Note: Add these methods after the initApp() method.
  6. Next, you must add event listeners on buttons in the UI and write code in these event handlers to execute specific methods on the StompClient object created earlier with arguments taken from text boxes defined in the UI. Add the following 3 lines to the initApp() method to associate handlers for connect and disconnect buttons.
    Replace:

    //TODO3: add handlers CONNECT buttons

    in the initApp() method with:

    //add event handlers for buttons: connect, disconnect
    connect.addEventListener("buttonDown", connectHandler)
    disconnect.addEventListener("buttonDown", disconnectHandler)

  7. Next, add implementations for these methods, which call into connect() and disconnect() methods on the StompClient object respectively. Add these after the initApp()method. Please note that the URL is hard coded to point to ws://localhost:8000/activemq, which is the default configuration for this demo, if you choose to configure a new service accept URL (defined in gateway-config.xml) you must change the value entered in the Location text box to match the one from the configuration file.

    private function connectHandler(e:Event):void {
      log("CONNECT: " + location.text + " " + username.text +"\n")
      client.connect(location.text, {username:username.text,     password:password.text})
      connect.enabled = false;
    }

    private function disconnectHandler(e:Event):void {
      log("DISCONNECT: " + location.text + " " + username.text +"\n")
      client.disconnect()
      disconnect.enabled = false;
    }

    Note: location, username and password are ids for text boxes defined in the UI.
  8. Next, add event listeners on Stomp subscription related buttons in the UI and write code in these event handlers to execute subscribe, send and unsubscribe methods on the StompClient object with arguments taken from text boxes defined in the UI. Add the following lines to end of the initApp() method to associate handlers for subscribe, send and unsubscribe buttons.
    Replace:

    //TODO4: add handlers SUBSCRIBE buttons

    in the initApp() method with:

    //add event handlers for buttons: subscribe, send, unsubscribe
    subscribe.addEventListener("buttonDown", subscribeHandler)
    send.addEventListener("buttonDown", sendHandler)
    unsubscribe.addEventListener("buttonDown", unsubscribeHandler)

  9. Next, add implementations for these methods, which call into subscribe(), send() and unsubscribe() methods on the StompClient object respectively.

    private function subscribeHandler(e:Event):void {
      log("SUBSCRIBE: " + subscription.text + "\n")
      client.subscribe(subscription.text, null, null)
    }

    private function sendHandler(e:Event):void {
      log("SEND: " + message.text + " " + subscription.text + "\n")
      client.send(message.text, subscription.text, null, null)
    }

    private function unsubscribeHandler(e:Event):void {
      log("UNSUBSCRIBE: " + subscription.text + "\n")
      client.unsubscribe(subscription.text, null, null)
    }

  10. Next, add event listeners on Stomp transaction related buttons in the UI and write code in these event handlers to execute begin, send, commit and abort methods on the StompClient object with arguments taken from text boxes defined in the UI. Add the following lines to the end of the initApp() method to associate handlers for subscribe, send and unsubscribe buttons.
    Replace:

    //TODO5: add handlers TRANSACTION buttons

    in the initApp() method with:

    //add event handlers for buttons: begin, sendMessage, commit, abort
    begin.addEventListener("buttonDown", beginHandler)
    commit.addEventListener("buttonDown", commitHandler)
    abort.addEventListener("buttonDown", abortHandler)
    sendMessage.addEventListener("buttonDown", sendMessageHandler)

  11. Next, add implementations for these methods after the initApp()method., which call into begin(), send(), commit() , and abort() methods on the StompClient object respectively.

    private function beginHandler(e:Event):void {
      log("BEGIN: " + transaction.text + "\n")
      client.begin(transaction.text, null, null)
    }

    private function sendMessageHandler(e:Event):void {
      log("SEND: " + transaction_message.text + " " +     transaction_destination.text + " " + transaction.text + "\n")
      client.send(transaction_message.text, transaction_destination.text,     transaction.text, null)
    }

    private function commitHandler(e:Event):void {
      log("COMMIT: " + transaction.text + "\n")
      client.commit(transaction.text, null, null)
    }

    private function abortHandler(e:Event):void {
      log("ABORT: " + transaction.text + "\n")
      client.abort(transaction.text, null, null)
    }

Congratulations! You just finished coding your ActionScript Stomp application using Adobe Flex. Now let us run it!

Note: The file stomp-completed.mxml, located in KAAZING_HOME/web/tutorials/stomp-actionscript contains a complete version of the file for your convenience. Rename the file to stomp.mxml before you compile it.

Starting Kaazing Gateway and Apache ActiveMQ

Before you can test the Stomp application you must get the runtime environment up and running. Refer to Getting Started for more information on how to install and run Kaazing Gateway and Apache ActiveMQ.

Compiling and Running the Stomp-Based Adobe Flex Application

Use the Adobe Flex 3 SDK to compile the Adobe Flex client. The stomp.mxml file that you have been changing is located in KAAZING_HOME/web/tutorials/stomp-actionscript directory. In a command prompt, navigate to that directory and execute the following command to generate the stomp.swf file:

ADOBE_FLEX_SDK_HOME/bin/mxmlc stomp.mxml -library-path+=KAAZING_HOME/lib/client/flex

The library-path argument should point to the directory that contains the Kaazing Flex client library file kaazing-enterprise-gateway-client-release-version.swc. This SWC file can be found in the Kaazing Gateway demo bundle in the directory KAAZING_HOME/lib/client/flex.

You can now execute this SWF file from the flash player or use a Web page to invoke it. To test your new Stomp application, point your browser to http://[localhost:port]/tutorials/stomp-actionscript/stomp-flash.html, which embeds the generated stomp.swf for testing purposes. For example, http://localhost:8000/tutorials/stomp-actionscript/stomp-flash.html. Your application should look like the finished application shown earlier.

As you try out the application, log messages display in the message console in the lower-right corner of the Stomp application.

Note: If you want to see two or more browsers communicate and you are running Kaazing Gateway on your local system, you can launch two or more browser instances. For example, Internet Explorer and Firefox.