Reverse Ajax, Part 4: Atmosphere and cometd

Source: Internet
Author: User
Tags glassfish

English Original: Reverse Ajax, part 4:atmosphere and CometD

 Objective

This series of articles shows how to develop event-driven Web applications using reverse Ajax technology, and part 1th describes reverse Ajax (Reverse Ajax), polling (polling), streaming (stream), comet, and long polling (long polling) The 2nd section describes how to use WebSocket to implement reverse Ajax, and discusses the limitations of using Comet and WebSocket Web servers, and the 3rd part explains that If you need to support multiple servers or provide users with a standalone Web application deployed on their own servers, there are some difficulties in implementing your own comet or websocket communication system. Even though the client's JavaScript code is simple, you need to use some exception handling, reconnection, and validation capabilities. On the server side, the absence of global APIs and the multiple Web server APIs have led to the need for frameworks, which brings a layer of abstraction, and part 3 also addresses Socket.io.

In this article, we understand atmosphere and cometd, which are the most well-known open source reverse AJAX libraries for Java servers.

You can download the source code used in this article.

  Pre-conditions

Ideally, to fully appreciate this article, you should have a good understanding of Javascrpit and Java. To run the examples in this article, you'll also need the latest version of Maven and JDK.

  Atmosphere Frame

Atmosphere is a Java technology framework that provides a common API to use the comet and WebSocket of many Web servers, including Tomcat, Jetty, GlassFish, Weblogic, Grizzly , Jbossweb, JBoss, and resin, which also supports any Web server that supports the Servlet 3.0 specification. In each of the frameworks mentioned in this series, atmosphere supports the largest number of servers.

The atmosphere can detect localized server-side APIs (for Comet and WebSocket), switch back to Servlet3.0 if available, or, for comet, fall back to a "managed" Asynchronous Pattern (but not the kind of scalability that jetty continuation). Atmosphere has been in existence for more than two years and is still at an active stage of development. It is used in large Web applications, such as Jira, which is one of the most famous problem trackers. Figure 1 shows the architecture of the atmosphere.

Figure 1. Atmosphere Architecture at a glance

Atmosphere is comprised of the atmosphere runtime, which provides a common API for all the different Web server solutions and standards. On top of that, the client can set up a simple servlet to access the API and reverse AJAX functionality through Google Web Toolkit (GWT). Alternatively, you can also use Jersey, a framework that implements the JSR-311 (Jax-rs specification). With the additional annotations provided, atmosphere can be used in restful services. Once you have configured the selected modules, you can access the Atomsphere runtime by implementing some classes (discussed later in this article). You can also choose to use some of the plug-ins provided, which add support for clustering, messaging, dependency injection, and more. If you are using a Web framework (Wecket, Struts, Spring MVC), you can use atmosphere's meteorservlet to transparently add reverse AJAX support. This servlet exposes a meteor object that can be retrieved within your controller to suspend or resume the request.

Atmosphere's strong stay on the server side: it provides a standard API that covers all the different solutions and methods for communicating with websocket or comet. Atmosphere does not use protocols between the client and server, such as Socket.io and cometd, both of which provide a client's JavaScript and a server-side servlet whose communication uses a specific protocol (handshake, message , confirmation, and Heartbeat). The goal of atmosphere is to provide a common communication channel on the server side. If you need to use a specific protocol, such as Bayeux (a protocol used by COMETD), you need to develop your own "handlers" in atmosphere. The cometd plugin does this: it leverages the atmosphere API to suspend and resume requests, and delegates cometd classes to manage COMETD traffic using the Bayeux protocol.

Atmosphere's jquery client library facilitates the establishment of connections, which automatically detects the best available transport modes (WebSocket or cometd). Atmosphere's jquery plugin is similar to the HTML5 WebSocket API, first you connect to the server side, register a callback to receive the information, and then you can push some data.

The source code in this article contains a atmosphere example that directly uses a handler that uses the atmosphere servlet. The code for the client is always the same, as is the code for the users in parts 1th, 2, and 3 of this series (using the comet long polling chat example). You may have used the atmosphere jquery plugin, but this is not required because atmosphere does not enforce any communication protocols. It is strongly recommended that you study other examples in the atmosphere project, especially those that use the JSR-311 annotation (Jersey), which really simplifies the programming of the handlers.

Listing 1. Atmospherehandler interface

[Java]View Plaincopy
    1. Public interface Atmospherehandler {
    2.   void ONrequest (Atmosphereresource Resource)
    3.   Throws IOException;
    4.   void Onstatechange (Atmosphereresourceevent event)
    5.   Throws IOException;
    6.   void Destroy ();
    7. }

The ONrequest method receives all requests from the client and decides whether to suspend or restore them (or do nothing), and sends an event that is received by the Onstatechange method each time a request is suspended or resumed, a broadcast is sent, or a timeout occurs.

The ONrequest method implementation of the comet Chat example is shown in Listing 2.

Listing 2. Atmospherehandler Interface--onrequest

[Java]View Plaincopy
  1. Broadcaster broadcaster = Broadcasterfactory.getdefault (). Lookup (
  2. Defaultbroadcaster. class, Chathandler.  class.getname (), true);
  3. Broadcaster.setscope (Broadcaster.SCOPE.APPLICATION);
  4. Resource.setbroadcaster (broadcaster);
  5. HttpServletRequest req = Resource.getrequest ();
  6. String user = (string) req.getsession (). getattribute ("user");
  7.   if (user! = null) {
  8.     if ("GET". Equals (Req.getmethod ())) {
  9. Resource.suspend (-1, false);
  10. } Else if ("POST". Equals (Req.getmethod ())) {
  11. String cmd = req.getparameter ("cmd");
  12. String message = Req.getparameter ("message");
  13.     if ("disconnect". Equals (cmd)) {
  14. Close (Resource);
  15. } Else if (message! = null && message.trim (). Length () > 0) {
  16. Broadcaster.broadcast ("[" + User + "]" + message);
  17. }
  18. }
  19. }

A typical practice is to suspend a GET request and use a POST request to send a message. When a message is received, the message is broadcast to all resources registered within the broadcaster. It can be noted that this example does not write anything to the HttpServlet output stream, and the broadcast or suspend behavior simply sends events received by other implementations, as shown in Listing 3:

Listing 3. Atmospherehandler Interface--onstatechange

[Java]View Plaincopy
  1. Broadcaster broadcaster = Broadcasterfactory.getdefault (). Lookup (
  2. Defaultbroadcaster. class, Chathandler.  class.getname (), true);
  3.   Client closed the connection.
  4.   if (event.iscancelled ()) {
  5. Close (Event.getresource ());
  6.     Return
  7. }
  8.   try {
  9. String message = (string) event.getmessage ();
  10.     if (Message! = null) {
  11. PrintWriter writer =
  12. Event.getresource (). GetResponse (). Getwriter ();
  13. Writer.write (message);
  14. Writer.flush ();
  15. }
  16. } finally {
  17.     if (!event.isresumedontimeout ()) {
  18. Event.getresource (). resume ();
  19. }
  20. }

Now that you have everything you need to run the Camet chat example, the important concept of atmosphere is that the resource object describes the connection, and the broadcaster is responsible for triggering the resource event and deciding when to suspend or resume a request. It is important to note that this example applies only to comet, and if you want to be able to use both websocket and comet, you should use some kind of client-side library and need a more sophisticated handler.

Table 1 lists the pros and cons of using the atmosphere framework.

Table 1. Advantages and disadvantages of atmosphere

1. Advantages

If you need to deploy a Web application on several Web servers that you cannot decide on yourself, because atmosphere supports many kinds of Web servers, your application's reverse AJAX capabilities can be significantly more powerful to work correctly.

On top of the original reverse AJAX communication without any protocol defined, because you want to develop or extend it, you will need a generic API.

2. Disadvantages

Without documentation on atmosphere architecture, projects, concepts, and APIs, these documents can be helpful if you need to drill down into the source code or analyze some of the provided examples. The API is highly technical and somewhat obscure compared to the simple API of other frameworks such as Socket.io and cometd. Even when using atmosphere annotations, some names and attributes are too professional.

Although there is a good abstraction on the server side, there is not a good client library. Because there is no agreement, all the other functions are left to the developer to implement. For a large, scalable Web application, if you need advanced time detection, validation, fallback, cross-domain functionality, especially when running on a mobile device, the current library is simply too simple. In this case, the cometd is more reliable; It leverages a communication protocol that can be used to activate certain control flows and error detection, all of which are provided internally within COMETD. If you need additional functionality, the COMETD JavaScript client with the Atomsphere cometd plugin is another good choice.

  COMETD Frame

The COMETD framework is an HTTP-based event-driven communication solution that has been in existence for several years, with version 2 adding support for annotation configuration and websocket. The COMETD framework provides a part of the Java server side and a portion of a Java client, as well as a JavaScript client library based on jquery and dojo. COMETD uses a standard communication protocol called Bayeux that allows you to activate certain extensions of message acknowledgement, Process Control, synchronization, and clustering.

The COMETD event-driven approach is well suited to the new concept of event-driven web development, and as with traditional desktop user interfaces, all component communications send notifications and receive events through a single bus, so all communication is asynchronous.

COMETD Frame:

1. There is a detailed description of the document

2. Examples and Maven prototypes are provided to facilitate project start-up

3. Provides a well-designed API to support extended development

4. Provides a cluster module called Oort, which provides the ability to run multiple cometd Web servers as nodes in a cluster, before which a load balancer adjusts the HTTP connection for large amounts of data.

5. Support fine-grained security policy configuration, we can specify which channel to send messages.

6. Good integration of spring and Google Guice (Dependency injection framework)

  Bayeux Protocol

The Byeux communication protocol is mainly implemented by HTTP, which provides a reactive bidirectional communication between the client and the server in an asynchronous way. The Bayeux protocol is based on the channel of message routing, from the client to the server side, from the server side to the client, or between the client (but through the server side), Bayeux is a publish-subscribe protocol. COMETD implements the Bayeux protocol, which provides an abstraction layer on top of comet and WebSocket transmissions to route requests through Bayeux.

  Server side and its internal

COMETD Bundles Three transports: JSON, Jsonp, and WebSocket, which depend on the jetty continuation and jetty WebSocket APIs. By default, COMETD is available in Jetty 6, 7, and 8, and in any server that supports the Servlet 3.0 specification. You can add and develop transports in the same way as extensions, you should be able to write transports to support the Grizzly WebSocket API and other protocols, and then add them to the steps involved in configuring the COMETD server. Figure 2 shows an overview of the main cometd blocks.

Figure 2. Overview of the architecture of COMETD

Figure 2 does not give a security layer to access the message channel.

The source code provided in this article includes a web app that uses cometd, a descriptor for this web app that contains the definition of the chat example in Listing 4.

Listing 4. Xml

[HTML]View Plaincopy
  1. <servlet>
  2. <servlet-name>cometd</servlet-name>
  3. <servlet-class>
  4. Org.cometd.java.annotation.AnnotationCometdServlet
  5. </servlet-class>
  6. <async-supported>true</async-supported>
  7. [...]
  8. <init-param>
  9. <param-name>services</param-name>
  10. <param-value>chatservice</param-value>
  11. </init-param>
  12. <init-param>
  13. <param-name>transports</param-name>
  14. <param-value>
  15. Com.ovea.cometd.websocket.jetty8.Jetty8WebSocketTransport
  16. </param-value>
  17. </init-param>
  18. </servlet>

COMETD this servlet supports multiple options for controlling global settings, such as the ability to set up transports and services. In this example, assuming you want to increase the WebSocket support for Jetty 8, the server-side COMETD service class Chatservice will control the chat rooms in which everyone will speak, as shown in Listing 5:

Listing 5. CometD Chatservice

[Java]View Plaincopy
  1. @Service
  2. Public Final class Chatservice {
  3. @Inject
  4. Bayeuxserver server;
  5. @PostConstruct
  6. void Init () {
  7. Server.addlistener (new Bayeuxserver.sessionlistener () {
  8. @Override
  9. Public void Sessionadded (serversession session) {
  10. [...]
  11. }
  12. @Override
  13. Public void Sessionremoved (Serversession session, Boolean timedout) {
  14. [...]
  15. }
  16. });
  17. }
  18. @Configure ("/**")
  19. void any (Configurableserverchannel channel) {
  20. Channel.addauthorizer (Grantauthorizer.grant_none);
  21. }
  22. @Configure ("/chatroom")
  23. void Configure (Configurableserverchannel channel) {
  24. Channel.addauthorizer (new Authorizer () {
  25. @Override
  26. Public Result Authorize (
  27. [..] //Check that the user are in session
  28. }
  29. });
  30. }
  31. @Listener ("/chatroom")
  32. void Appenduser (Serversession remote,
  33. Servermessage.mutable message) {
  34. [...]
  35. }
  36. }

Listing 5 illustrates some of the key features of cometd, including:

1. Dependency Injection

2. Life Cycle Management

3. Global Channel Configuration

4. Security Management

5. Message translation (before adding the user name to all messages)

6. Session Management

On the client side, the example does not activate any extensions-just the original cometd code, as shown in Listing 6:

Listing 6. COMETD Client-side code

[JavaScript]View Plaincopy
  1. First create the Cometd object and configure it
  2. var cometd = New $.cometd (' cometd chat client ');
  3. Cometd.configure ({
  4. Url:document.location + ' cometd ',
  5. LogLevel: ' Debug '
  6. });
  7. cometd.websocketenabled = ' WebSocket ' in window;
  8. Then register some listeners. Description Channel (has
  9. Those in the/meta/format are specific reserved channels)
  10. Cometd.addlistener ('/meta/disconnect ', function (message) {
  11. [...]
  12. });
  13. Cometd.addlistener ('/meta/connect ', function (message) {
  14. [...]
  15. });
  16. Then start a connection that you can use:
  17. Cometd.handshake ();
  18. Then subscribe to:
  19. Cometd.subscribe ('/chatroom ', function (event) {
  20. [...] //Event.data store messages
  21. });
  22. We end up sending data to chat rooms in this way:
  23. Cometd.publish ('/chatroom ', msg);

COMETD's client API is easy to use and understand, while preserving the power of functionality and scalability. This article covers only the main parts of the Web application, so you can learn more about the powerful features of COMETD by studying example applications.

Table 2 lists the pros and cons of using the COMETD framework.

Table 2. Advantages and disadvantages of cometd

1. Advantages

From the client to the server side, and from a separate Java client to the server side, COMETD provides a complete solution. The framework has detailed documentation, a good API, and is very easy to use. Most importantly, it has an event-driven approach. Cometd and Bayeux are an integral part of many event-driven applications, and other reverse Ajax frameworks do not provide any event-driven mechanisms that enable end users to develop their own custom solutions.

COMETD supports many of the necessary features, such as reconnection, reliable timeout detection, fallback, batching, message acknowledgement, and much more that you won't find in other reverse Ajax frameworks. COMETD allows you to achieve the most reliable, low-latency communication.

2. Disadvantages
In addition to jetty for Comet (TOMCAT), COMETD does not currently support any servlet 2.5 containers, nor does it support glassfish/grizzly WebSocket.

 Conclusion

Atmosphere and cometd are stable, open-source, reverse Ajax solutions, and we chose cometd in Ovea because we have developed scalable event-driven applications for mobile devices within a clustered environment, and we have full control of our infrastructure (we use jetty). However, without additional development, cometd may not be the best option if you are selling web apps and want your reverse AJAX capabilities to work on as many servers as possible. But now as more and more Web applications begin to support the Servlet 3.0 specification, COMETD's limitations are trending down. When it comes to the transport layer, the remaining major differences depend on support for websocket.

  Code download

  Reverse_ajaxpt4_source.zip

Reverse Ajax, Part 4: Atmosphere and cometd

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.