Implementing Web messaging: Connect Ajax clients to near-real-time data with WebSphere Application Server Community Edition Skill Level: Intermediate Padmashree Kadaba Sampathkumar ([email protected]) System Software Engineer IBM 25 Aug 2010 Applications that depend on near-real-time data -- like stock quotes, health-monitoring systems, sports updates, news alerts, and more -- are becoming more and more popular and essential. This article describes how you can create such an application using IBM® WebSphere® Application Server Community Edition and the Web messaging service component of the Feature Pack for Web 2.0. Step through the tasks and issues you might encounter creating a sports community application that reports live score updates, and learn about the low latency server-to-browser event push technique known as Comet. Introduction The Web messaging service for IBM WebSphere Application Server Community Edition (hereafter referred to as Community Edition) provides support for low latency event push from server to the browser. It is a publish/subscribe implementation wherein the server sends (publishes) the data asynchronously and the subscribers receive the updates they are interested in, enabling the data updates and events to be delivered dynamically to Web browsers from Java™ Messaging Service (JMS) topics. In the publish/subscribe mechanism shown in Figure 1, the publisher publishes the data to various topics and the subscribers receive updates of interest. For example, Subscriber B receives the updates from both Topic 1 and Topic 2, while Subscribers A and C are only interested in updates from one topic. ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition ©CopyrightIBMCorporation2010.Allrightsreserved. Page1of27 developerWorks® ibm.com/developerWorks Figure 1. Publish/subscribe mechanism Client/server communication is achieved through the Bayeux protocol, which is a JSON (JavaScript™ Object Notation) based protocol used for sending asynchronous messages over HTTP with low latency between Web server and browser. JSON is a lightweight data-exchange format. The client side support for the Bayeux protocol is provided by the Dojo Toolkit. The Web messaging service bridges incoming Bayeux requests to JMS topics enabling Web services or JMS clients to publish events to the Bayeux-enabled Web clients. (See Resources for more information on the Bayeux protocol and Dojo Toolkit.) Bayeux implementations support a specific HTTP method called long polling. Long polling is a technique that optimizes traditional polling to reduce latency. In a long polling request, a client sends a request to a server to retrieve available information. The server checks for any available updates and if there are no updates, the server delays completing the HTTP request until either there is information available or a timeout occurs. If the server doesn’t have any update during a timeout event, it sends back a no-data-available response indicating the client should re-send the request. To illustrate this, this article walks through a sample application that uses the Web messaging service to connect an Ajax client to data updated in near real time. (For the purpose of this example, the data is randomly generated by the application to simulate real time updates.) This article assumes that you have knowledge of Web application development, JavaScript, Dojo and some familiarity with Eclipse. In addition, you need to have the WebSphere Application Server Feature Pack for Web 2.0 installed in a Community Edition environment so that you have access to these JAR files for the sample application: ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition Page2of27 ©CopyrightIBMCorporation2010.Allrightsreserved. ibm.com/developerWorks developerWorks® • WebMsgWASCE.jar is used to provide the Web messaging service to the application. It can be located in the <web20_install>/MessagingService/lib folder. • JSON4J.jar is used for the JSON processing required in the application. It can be located in the <web20_install>/JSON4J/lib folder. See Resources for information on downloading and installing Community Edition and the Web2.0 feature pack. Understanding polling methods In the traditional polling method, the client sends a request to the server and always either gets an immediate response if the server has any updated data, or a no-data-available response. The client in turn sends another request after a predetermined interval (poll interval) and this process continues until there is an update from the server. Disadvantages of this technique include an inefficient use of network bandwidth and slow speed. An alternative to this technique is long polling, which can avoid both these problems. With long polling, the client requests information from the server in a manner that is similar to traditional polling. However, if the server does not have any information, it holds the request and waits for an update to be available for the client. Once the information is available, it sends the response back to the client. The client will then immediately send another request to the server. Thus, the client avoids sending multiple requests for a single response, and improves efficiency of the network bandwidth. (Figure 2) Figure 2. Traditional polling vs. long polling However, long polling also has its limitations: Theterm"Comet"wascoinedbyAlexRussell.CometisaWeb ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition ©CopyrightIBMCorporation2010.Allrightsreserved. Page3of27 developerWorks® ibm.com/developerWorks applicationmodelthatenablesWebserverstosendthedatatothe clientwithouthavingtoexplicitlyrequestit.Cometcomesintwo flavors:streamingandlongpolling.TheWebmessagingfeaturein theFeaturePackforWeb2.0usesTomcatCometsupport, availableinTomcatversions6.0andlater. • Two-connection limit: Current HTTP client implementation recommends permitting only two connections between a client and a server. Therefore, if the browser session has two connections already, any further connection requests have to wait until one of the two connections is finished. One way to alleviate this problem is to multiplex all events onto the same server connection. This is effectively done by Comet and Cometd, a multiplex protocol and architecture. • Thread per connection: In long polling, the server holds the request until there are any updates or a timeout, which means freezing the connection -- and, in turn, the thread -- until a response or a timeout occurs. Traditional I/O associates a thread with every connection, and usually Web servers have a limited number of threads. Once all threads are used, any new requests are ignored, thinking the server is busy. This poses a problem if you want to scale an application to thousands of clients. An alternative is to tie up the thread per request so that it can be returned to the thread pool once the request processing is done. In long polling, however, a client would have an outstanding request to the server at any point of time. Thus, the server again needs one or more threads for every client, and again there are problems with scaling. The Tomcat solution to this problem is Advanced IO. Tomcat uses NIO (Non-blocking IO) to keep the connection alive without wasting the waiting threads. To facilitate NIO in a servlet, it uses an event-based API (CometProcessor) that initiates the appropriate reading and writing actions on the open connections at the right time. Comet support enables the servlet to process IO asynchronously, receiving the event when data is available in the server, and writing data asynchronously. Let’s stop for a moment and review some terms to ensure a basic understanding before moving on: • Server push is a mechanism of sending the data from server to client in an asynchronous fashion. • Long polling is a polling technique in which the server will delay completing the HTTP response until either an update is ready for the client or a timeout occurs. • Comet is a low latency data transfer technique that is event driven and ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition Page4of27 ©CopyrightIBMCorporation2010.Allrightsreserved. ibm.com/developerWorks developerWorks® uses the server push mechanism over the HTTP protocol. • CometD is a project undertaken by the Dojo Foundation to provide multiple client and server implementations that implement the Bayeux protocol. • NIO, also called asynchronous IO, enables the processing of other requests to continue before the current request processing is completed. • Bayeux protocol is a protocol for transporting asynchronous messages (primarily over HTTP) with low latency between a Web server and Web clients. The sample application The sample application described here (and included with this article for download) is a sports application that subscribes to the channels of two soccer teams and displays updates of the teams’ scores. The sample generates random values as scores to update the Web client to simulate near-real-time events. The Web messaging service library is used to incorporate the publish/subscribe feature in the application. Before you begin with the application, you need to configure the NIO connector in Community Edition. See the MessagingService documentation available in the installed directory of the Web2.0 feature pack, <web20_install>/MessagingService. With that complete, you can continue with your sample application development using the Web messaging service. The steps presented in the remainder of this article describe this process. 1. Create a Web application a. In Eclipse, Create a New Dynamic Web Project (Figure 3) and call it SportsApp (Figure 4). Make sure that Add project to an EAR is unchecked, then click Finish. Figure 3. Create dynamic Web project ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition ©CopyrightIBMCorporation2010.Allrightsreserved. Page5of27 developerWorks® ibm.com/developerWorks Figure 4. Name Web project ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition Page6of27 ©CopyrightIBMCorporation2010.Allrightsreserved. ibm.com/developerWorks developerWorks® b. Copy the WebMsgWASCE.jar and JSON4J.jar to the lib folder of the project. c. Insert the Dojo Toolkit into the Web module. The Web client requires dojox.cometd libraries to connect to the Bayeux server. The Dojo Toolkit can be located at <web20_install>/AjaxClientRuntime_1.X. The result is shown in Figure 5. Figure 5. Layout of the application ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition ©CopyrightIBMCorporation2010.Allrightsreserved. Page7of27 developerWorks® ibm.com/developerWorks 2. Configure Web messaging service a. Create a servlet called ScoreServlet and specify the Java package com.ibm.webmsg.sample in the src folder (Figure 6). The servlet extends BayeuxServlet provided by Web messaging service. Click Next. Figure 6. Create servlet ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition Page8of27 ©CopyrightIBMCorporation2010.Allrightsreserved. ibm.com/developerWorks developerWorks® b. Edit the URL mapping to /scoreServlet and click Finish (Figure 7). Figure 7. Edit URL mapping ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition ©CopyrightIBMCorporation2010.Allrightsreserved. Page9of27 developerWorks® ibm.com/developerWorks c. In ScoreServlet, set the necessary configuration properties and register the URI that is used for the publish/subscribe mechanism (Listing 1). Listing 1. ScoreServlet public class ScoreServlet extends BayeuxServlet { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(ScoreServlet.class.getName()); public void registerURL() { getServletUtil().addClientManager("/scoreServlet", clientManager); logger.log(Level.INFO, "Registered the URL for comet requests."); } public void setProperties() { setCometTimeout(60000); setClientPollInterval(0); setRouterType(JMS); setClientsCanPublish(false); logger.log(Level.INFO, "Configured properties for score board requests."); } } In the registerURL() method, you register the servlet URI (/scoreServlet). This is used by the Web messaging service for Comet requests. The ConnectAjaxclientstonear-real-timedatawithWebSphereApplicationServerCommunityEdition Page10of27 ©CopyrightIBMCorporation2010.Allrightsreserved.
Description: