Reverse Ajax, Part 1: Atmosphere and cometd)

Source: Internet
Author: User
Tags glassfish

Preface

This series of articles demonstrate how to use reverse Ajax technology to develop event-driven Web applications. Part 1 describes reverse Ajax (reverse Ajax), polling (polling), streaming (streaming) comet and long polling; Part 1 describes how to use websocket to implement reverse Ajax and discusses the limitations of web servers using comet and websocket; part 1 describes whether to support multiple servers or provide users with an independent web application deployed on their own servers, it may be difficult to implement your own comet or websocket communication system. Even if the client's JavaScript code is simple, you need to use some exception handling, reconnection, and validation functions. On the server side, the lack of global APIs and a variety of Web Server APIs have led to requirements for the Framework, which brings an abstraction. Socket. Io is also discussed in Part 1.

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

You can download the source code used in this article.

Prerequisites

Ideally, If You Want To fully understand this article, you should have a certain understanding of javascrpit and Java. To run the example in this article, you also need the latest version of Maven and JDK.

Atmosphere framework

Atmosphere is a Java technical framework that provides common APIs to use Comet and websocket of many web servers, these web servers include tomcat, Jetty, glassfish, WebLogic, Grizzly, jbossweb, JBoss, and resin. They also support any web servers that support servlet 3.0 specifications. Among the frameworks mentioned in this series, atmosphere supports the most servers.

Atmosphere can detect localized server-side APIs (for Comet and websocket). For comet, if available, it switches back to servlet3.0; or, it is still for Comet, it will be rolled back to a "managed" asynchronous mode (but not as scalable as jetty continuation ). Atmosphere has been in existence for more than two years and is still in an active development stage. It is used in large-scale Web applications, such as Jira, which is the most famous issue tracker. Figure 1 shows the atmosphere architecture.

Figure 1. Atmosphere Architecture Overview

Atmosphere consists of the atmosphere runtime. It provides a common API for all different Web server solutions and standards. On this basis, the client can set a simple servlet to use Google Web Toolkit (GWT) to access this API and reverse Ajax functions. Alternatively, you can use jersey, a framework that implements a JSR-311 (JAX-RS Specification. With the additional annotations provided, atmosphere can be used in restful services. After the selected module is configured, You can implement some classes to access the Atomsphere Runtime (this article will discuss later ). You can also choose to use some provided plug-ins that support clusters, messages, and dependency injection. If you are using a Web Framework (wecket, struts, spring
MVC), you can use the meteorservlet of atmosphere to transparently add reverse Ajax support. This servlet exposes a meteor object that can be retrieved within your controller to suspend or restore requests.

Atmosphere is powerful on the server: it provides a standard API that covers all different solutions and methods for communicating with websocket or comet. Atmosphere does not use the protocol between the client and the server, such as socket. io and cometd, both of which provide JavaScript on the client side and servlet on the server side, their communication uses a specific protocol (handshake, message, confirmation, and heartbeat ). Atmosphere aims to provide a common communication channel on the server side. If you need to use a specific protocol, for example, Bayeux (a protocol used by cometd), you need to develop your own "handler" in atmosphere ". The cometd plug-in does this: it uses the atmosphere API to suspend and restore requests, and delegates the cometd class to manage cometd communication using the Bayeux protocol.

The jquery client library provided by atmosphere facilitates connection establishment. It can automatically detect the best available transmission modes (websocket or cometd ). The jquery plug-in of atmosphere is similar to the HTML5 websocket API. First, you connect to the server, register a callback to receive information, and then you can push some data.

The source code in this article contains an atmosphere example, which directly uses a processing program using the atmosphere servlet. The client code is always the same. It is the same as the code of some users in the 1st, 2, and 3 Series (chat example using comet long polling ). You may have used the jquery plug-in of atmosphere, but this is not necessary, because atmosphere does not force any communication protocol. It is strongly recommended that you take a look at other examples of the atmosphere project, especially those using JSR-311 annotations (Jersey), which really simplify the compilation of the processing program.

Listing 1. atmospherehandler Interface

public interface AtmosphereHandler {  void onRequest(AtmosphereResource resource)  throws IOException;  void onStateChange(AtmosphereResourceEvent event)  throws IOException;  void destroy();}

The onrequest method receives all requests from the client and determines whether to suspend or recover them (or do nothing). Each time a request is suspended or resumed, a broadcast is sent, or a timeout occurs, an event received by the onstatechange method is sent.

The onrequest method of the comet chat example is implemented in Listing 2.

Listing 2. atmospherehandler interface -- onrequest

Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(  DefaultBroadcaster.class, ChatHandler.class.getName(), true);  broadcaster.setScope(Broadcaster.SCOPE.APPLICATION);  resource.setBroadcaster(broadcaster);  HttpServletRequest req = resource.getRequest();  String user = (String) req.getSession().getAttribute("user");  if (user != null) {    if ("GET".equals(req.getMethod())) {      resource.suspend(-1, false);    } else if ("POST".equals(req.getMethod())) {      String cmd = req.getParameter("cmd");      String message = req.getParameter("message");    if ("disconnect".equals(cmd)) {      close(resource);    } else if (message != null && message.trim().length() > 0) {      broadcaster.broadcast("[" + user + "] " + message);    }  }}

A typical practice is to suspend GET requests and use post requests to send messages. When a message is received, the message is broadcast to all resources registered in the broadcaster. It can be noted that this example does not write anything into the httpservlet output stream. The broadcast or suspension behavior only sends events received by other implementation methods, as shown in listing 3:

Listing 3. atmospherehandler interface -- onstatechange

Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(  DefaultBroadcaster.class, ChatHandler.class.getName(), true);  // Client closed the connection.   if (event.isCancelled()) {    close(event.getResource());    return;  }  try {    String message = (String) event.getMessage();    if (message != null) {      PrintWriter writer =      event.getResource().getResponse().getWriter();      writer.write(message);      writer.flush();    }  } finally {    if (!event.isResumedOnTimeout()) {      event.getResource().resume();  }}

Now you have all the requirements for running camet chat examples. In summary, some important concepts of atmosphere are: Resource Object Description connection, the broadcaster is responsible for triggering resource events and deciding when to suspend or resume a request. Note that this example only applies to comet. To use websocket and Comet, you must use a client library and a more complex processing program.

Table 1 lists the advantages and disadvantages 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, because atmosphere supports many web servers, so the chances of your application's reverse Ajax function working correctly are greatly increased.

In the absence of original reverse Ajax communication that defines any protocol, you need a common API to develop or expand it.

2. Disadvantages

There is a lack of documentation on the atmosphere architecture, projects, concepts, and APIs. It is helpful to go deep into the source code or analyze some examples provided. Compared with simple APIs of other frameworks such as socket. Io and cometd, the APIs are very technical and obscure. Some names and attributes are too professional even when using the atmosphere annotation.

Although there is a good abstraction on the server side, there is no good client library. Because there is no protocol, all other functions are left for developers to implement. For a large and scalable Web application, if you need advanced time detection, validation, rollback, cross-domain, and other functions, especially when running on mobile devices, the current database is too simple. In this case, cometd is more reliable; it uses a communication protocol that can be used to activate certain control flows and error detection, all of which are provided inside cometd. If you need additional features, using the cometd JavaScript client in the Atomsphere cometd plug-in is another good choice.

Cometd framework

The cometd framework is an HTTP-based event-driven communication solution that has existed for several years. Its version 2 adds support for annotation configuration and websocket. The cometd framework provides a Java server and a Java client, as well as JavaScript client libraries based on jquery and dojo. Cometd uses a standard communication protocol called Bayeux that allows you to activate certain extensions such as message validation, process control, synchronization, and clusters.

The event-driven method of cometd is very suitable for the new concept of event-driven web development. Like the traditional desktop user interface, all components communicate with each other to send notifications and receive events through a bus, therefore, all communications are asynchronous.

Cometd framework:

1. Detailed documentation

2. Provides examples and Maven prototypes to facilitate project startup.

3. A well-designed API is provided 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 that, a server Load balancer used to adjust HTTP connections with large data volumes.

5. fine-grained security policy configuration is supported. We can specify which channel to send messages.

6. Well integrated spring and Google guice (dependency injection Framework)

Bayeux Protocol

Byeux communication protocol is mainly implemented through HTTP. It provides a responsive bidirectional communication between the client and the server. The Bayeux protocol is based on the message routing channel. It is transmitted from the client to the server, from the server to the client, or between clients (but through the server ), bayeux is a publish-subscribe protocol. Cometd implements the Bayeux protocol, which provides an abstraction layer for routing requests through Bayeux over the transmission of comet and websocket.

Server and its internal

Cometd is bundled with three types of transmission: JSON, jsonp, and websocket, which depend on Jetty continuation and jetty websocket APIs. By default, cometd is available in jetty 6, 7, and 8, and any server that supports servlet 3.0 specifications. You can add and develop transmission in the same way as expansion. You should be able to write transmission to support grizzly websocket API and some of its protocols, add them to the cometd server configuration step. Figure 2 shows an overview of the major cometd blocks.

Figure 2. Architecture Overview of cometd

Figure 2 does not provide a security layer for accessing the Message channel.

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

Listing 4. Web. xml

<servlet> <servlet-name>cometd< /servlet-name> <servlet-class> org.cometd.java.annotation.AnnotationCometdServlet</servlet-class> <async-supported>true< /async-supported> [...]<init-param> <param-name>services< /param-name> <param-value>ChatService< /param-value> </init-param> <init-param> <param-name>transports< /param-name> <param-value> com.ovea.cometd.websocket.jetty8.Jetty8WebSocketTransport</param-value> </init-param> </servlet>

The cometd servlet allows you to control multiple global options, such as setting transmission and service capabilities. In this example, if you want to add websocket support for jetty 8, the server-side cometd service chatservice controls the chat rooms in which everyone will speak, as shown in listing 5:

Listing 5. cometd chatservice

@Servicepublic final class ChatService {@InjectBayeuxServer server;@PostConstructvoid init() {server.addListener(new BayeuxServer.SessionListener() {@Overridepublic void sessionAdded(ServerSession session) {[...]}@Overridepublic void sessionRemoved(ServerSession session, boolean timedout) {[...]}});}@Configure("/**")void any(ConfigurableServerChannel channel) {channel.addAuthorizer(GrantAuthorizer.GRANT_NONE);}@Configure("/chatroom")void configure(ConfigurableServerChannel channel) {channel.addAuthorizer(new Authorizer() {@Overridepublic Result authorize([..] // check that the user is in session }});}@Listener("/chatroom")void appendUser(ServerSession remote,ServerMessage.Mutable message) {[...]}}

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

1. Dependency Injection

2. lifecycle management

3. Global Channel Configuration

4. Security Management

5. Message conversion (before adding a user name to all messages)

6. session management

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

Listing 6. cometd client code

// Create a cometd object and configure it var cometd = new $. cometd ('cometd chat client'); cometd. configure ({URL: document. location + 'metd', loglevel: 'debug'}); cometd. websocketenabled = 'websocket 'in window; // register some listeners. Description of the channel (with the // META/format of specific reserved channels) cometd. addlistener ('/META/disconnect', function (Message) {[...]}); cometd. addlistener ('/META/connect', function (Message) {[...]}); // start a usable connection: cometd. handshake (); // subscribe to: cometd. subscribe ('/chatroom', function (event) {[...] // event. data storage message}); // We finally send data to the chat room in this way: cometd. publish ('/chatroom', MSG );

Cometd client APIs are easy to use and understand, while retaining powerful functions and scalability. This article only covers the main part of the Web application, so we can better understand the powerful functions of cometd through the study of examples and applications.

Table 2 lists the advantages and disadvantages of using the cometd framework.

Table 2. Advantages and Disadvantages of cometd

1. Advantages

From the client to the server, and from an independent Java client to the server, cometd provides a complete solution. The Framework provides detailed documentation, provides a good API, and is very easy to use. Most importantly, it has an event-driven method. Cometd and Bayeux are components of many event-driven applications. Other reverse Ajax frameworks do not provide any event-driven mechanism, so that end users have to develop their own custom solutions.

Cometd supports many required functions, such as reconnection, reliable timeout detection, rollback, batch processing, message validation, and more functions that you will not find in other Reverse Ajax frameworks. Cometd allows you to achieve the most reliable and low-latency communication.

2. Disadvantages
Except jetty for Comet (Tomcat), cometd currently does not support any servlet 2.5 containers, nor does it support glassfish/grizzly websocket.

Conclusion

Both atmosphere and cometd are stable and open-source reverse Ajax solutions. We chose cometd in ovea, because we developed scalable event-driven applications for mobile devices in a cluster environment, we have full control over the infrastructure (we use jetty ). However, without additional development, if you are selling web applications and want your reverse Ajax functions to work on as many servers as possible, cometd may not be the best choice. But as more and more web applications begin to support the servlet 3.0 specification, the limitations of cometd are declining. When it comes to the transport layer, the remaining major differences depend on the support for websocket.
Transferred from: Http://select.yeeyan.org/view/213582/217948

Code download

  Reverse_ajaxpt4_source.zip

Related Article

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.