Reverse Ajax 30 Minute quick Master _ajax related

Source: Internet
Author: User
Tags http request

Scenario 1: When there are new messages, the Web page automatically pops up the message without requiring the user to manually refresh the Inbox.

Scenario 2: When the user's mobile phone scan completes the two-dimensional code in the page, the page will automatically jump.

Scenario 3: Anyone who speaks in an environment like a chat room can instantly see information from all logged-in users.

Compared with the traditional MVC model request must be initiated from the client by the server response, using reverse Ajax can simulate the server-side initiative to push events to the client to improve the user experience. This article will discuss reverse Ajax technology in two parts, including: Comet and WebSocket. The article aims to demonstrate how to achieve the above two technical means, Struts2 or SPRINGMVC application is not involved. In addition, the servlet configuration is annotated, the relevant knowledge can refer to other information.

First, Comet (best compatible means)

Comet is essentially the concept of being able to send data from the server side to the client. In a standard HTTP Ajax request, the data is sent to the server side, and reverse Ajax simulates an AJAX request in some particular way, so that the server can send events to the client as quickly as possible. Because ordinary HTTP requests tend to accompany page jumps, push events require browsers to stay on the same page or frame, so the comet implementation can only be done through Ajax.

It is implemented as follows: When the page loads, an AJAX request is sent to the server, and the server gets the request and saves it in a thread-safe container (usually a queue). The server side can still respond to other requests normally. When an event needs to be pushed, the server traverses the request in the container and deletes it after returning the reply. So all the browsers that stay on the page get the answer and send the AJAX request again, repeating the process.

<%@ page language= "java" contenttype= "text/html;
Charset=utf-8 "pageencoding=" UTF-8 "%> <% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/"; %> <! DOCTYPE html>  

We note that requests sent by BTN do not actually require a response. The key to the whole process is the need for the client to always keep the server on the Connect () request. The server side first needs to support this asynchronous response, fortunately most of the servlet containers so far have provided good support. Here's a tomcat example:

Package servlet;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Queue;
Import Java.util.concurrent.ConcurrentLinkedQueue;
Import Javax.servlet.AsyncContext;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; @WebServlet (value= "/longpolling", asyncsupported=true) public class Comet extends HttpServlet {private static final Queu
e<asynccontext> connections = new concurrentlinkedqueue<asynccontext> (); @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {S
Tring method = Req.getparameter ("method");
if (Method.equals ("OnOpen")) {OnOpen (req, resp);} else if (Method.equals ("OnMessage")) {OnMessage (req, resp);}} private void OnOpen (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {AsyncContext context = Req.startasync ();
Context.settimeout (0);
Connections.offer (context); } private void OnMessage (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {String m
sg = Req.getparameter ("msg");
Broadcast (MSG); Private synchronized void Broadcast (String msg) {for (Asynccontext context:connections) {httpservletresponse respons
E = (httpservletresponse) context.getresponse ();
try {printwriter out = Response.getwriter (); Out.print (msg); Out.flush (); Out.close (); Context.complete ();
Connections.remove (context);
catch (IOException e) {e.printstacktrace ();}}  }
}

Concurrentlinkedqueue is a thread-safe implementation of queue queues, which is used here as a container for saving requests. Asynccontext is an asynchronous environment supported by Tomcat, and the objects used by different servers are slightly different. The object supported by jetty is continuation. A request to complete a broadcast needs to end the related request through Context.complete () and delete the queue using the Connections.remove (context).

Ii. WebSocket (support from HTML5)

Comet with HTTP Long polling is the best way to reliably reverse Ajax, since all browsers now provide support for this.

WebSockets in HTML5 is a reverse Ajax technology that is newer than Comet. WebSockets supports two-way, Full-duplex communication channels, and many browsers (Firefox, Google Chrome, and Safari) support it. A connection is through an HTTP request (also known as a websockets handshake) and some special headers (header). The connection is always active, and you can write and receive data in JavaScript just as you would with the original TCP socket.

Start the WebSocket URL by entering ws://or wss://(on SSL). As shown in figure:

First of all: WebSockets is not a good support in all browsers, it is obvious that IE dragged its hind legs. So when you plan to use this technology, you must consider the user environment, if your project is directed to the Internet or to include mobile users, I urge you to think twice.

Second: The request provided by WebSockets differs from the ordinary HTTP request, which is a full-duplex communication and is always active (if you do not close it). This means you can save a lot of resources by not having to send a request again to the server each time you get an answer.

<%@ page language= "java" contenttype= "text/html;
Charset=utf-8 "pageencoding=" UTF-8 "%> <% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";
String ws = "ws://" + request.getservername () + ":" + request.getserverport () + path + "/"; %> <! DOCTYPE html>  

jquery does not provide better support for websocket, so we have to use JavaScript to write part of the code (fortunately it's not complicated). And playing some of the most common servers can support WS requests, taking Tomcat as an example. In version 6.0, the Websocketservlet object has been labeled as a @java.lang.deprecated,7.0 version to support jsr365-provided implementations, so you must use annotations to complete the configuration.

 package servlet; import java.io.IOException; import java.util.Queue; import
Java.util.concurrent.ConcurrentLinkedQueue;
Import Javax.websocket.OnClose;
Import Javax.websocket.OnMessage;
Import Javax.websocket.OnOpen;
Import javax.websocket.Session;
Import Javax.websocket.server.ServerEndpoint; @ServerEndpoint ("/websocket") public class WebSocket {private static final queue<websocket> connections = new Concu
Rrentlinkedqueue<websocket> ();
Private session session;
@OnOpen public void OnOpen (Session sessions) {this.session = session;
Connections.offer (this); @OnMessage public void OnMessage (String message) {broadcast (message);} @OnClose public void OnClose () {connections.re
Move (this); Private synchronized void Broadcast (String msg) {for (WebSocket point:connections) {try {Point.session.getBasicRemo
Te (). SendText (msg); catch (IOException e) {connections.remove (point); try {point.session.close ();} catch (IOException e1) {}}} 

Iii. Summary (from request to push)

In a traditional communication scenario, if system A requires information from System B, it sends a request to system B. System B will process the request, and system A will wait for the response. When processing is complete, the response is sent back to system A. In synchronous communication mode, resource usage is less efficient because it wastes processing time while waiting for a response.

In asynchronous mode, System A subscribes to the information it wants to obtain from system B. System A can then send a notification to system B, or it can return information immediately, while system a can handle other transactions. This step is optional. In an event-driven application, you typically do not have to ask other systems to send events because you do not know what these events are. After system B publishes the response, System A receives the response immediately.

The WEB framework used to rely on traditional "request-response" mode, which causes page refreshes. With the advent of Ajax, Reverse Ajax, and WebSocket, the concept of event-driven architecture can now be easily applied to the WEB, benefiting from coupling, scalability, and reactivity (reactivity). A better user experience can also lead to new business opportunities.

The above is a small set to introduce the reverse Ajax 30 minutes quick grasp, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.