Reverse Ajax: 30 minutes quick control, reverse ajax30 minutes

Source: Internet
Author: User

Reverse Ajax: 30 minutes quick control, reverse ajax30 minutes

Scenario 1: when a new email is sent, a prompt message is displayed on the webpage without manual refreshing of the inbox.

Scenario 2: when a user's mobile phone scans the QR code on the page, the page automatically jumps.

Scenario 3: anyone in a chat room can speak, and all logged-on users can see the information instantly.

Compared with traditional MVC model requests that must initiate responses from the client to the server, reverse Ajax can simulate the server to actively push events to the client to improve user experience. This article will discuss reverse Ajax technology in two parts, including Comet and WebSocket. The purpose of this article is to demonstrate how to implement the above two technical means. Applications in Struts2 or SpringMVC are not involved. In addition, Servlet configurations are annotated. For more information, see other materials.

I. Comet (best compatibility means)

In essence, Comet is a concept that can send data from the server to the client. In a standard HTTP Ajax request, data is sent to the server. In reverse Ajax, a specific method is used to simulate an Ajax request. In this case, the server can send events to the client as quickly as possible. Because normal HTTP requests are usually accompanied by PAGE jumps, and the push event requires the browser to stay on the same page or framework, the implementation of Comet can only be done through Ajax.

The implementation process is as follows: when a page is loaded, an Ajax request is immediately sent to the server. The server obtains the request and saves it in a thread-Safe Container (usually a queue ). At the same time, the server can still respond to other requests normally. When the event to be pushed arrives, the server traverses the requests in the container and deletes the requests after the response is returned. Therefore, all the browsers staying on the page will get the response and send the Ajax request again. Repeat the above 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 noticed that the request sent by btn does not need to receive a response. The key to the entire process is that the client always requires the server to maintain the connect () request. The server first needs to support this asynchronous response method. Fortunately, most Servlet containers have provided good support so far. The following uses Tomcat as an 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 Queue<AsyncContext> CONNECTIONS = new ConcurrentLinkedQueue<AsyncContext>();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String 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 msg = req.getParameter("msg");broadcast(msg);}private synchronized void broadcast(String msg) {for (AsyncContext context : CONNECTIONS) {HttpServletResponse response = (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();}}}} 

Concurrentincluqueue is a thread security implementation of the Queue. It is used as the container to save the request. AsyncContext is an asynchronous environment supported by Tomcat, and the objects used by different servers are slightly different. Jetty supports Continuation. To complete a broadcast request, you must use context. complete () to end the request and use CONNECTIONS. remove (context) to delete the queue.

Ii. WebSocket (supported by HTML5)

The use of HTTP long polling Comet is the best way to reliably implement reverse Ajax, because all browsers now provide support in this regard.

WebSockets appears in HTML5, which is a reverse Ajax technology newer than Comet. WebSockets supports two-way, full-duplex communication channels, and many browsers (Firefox, Google Chrome, and Safari) also support it. The connection uses HTTP requests (also known as WebSockets handshake) and some special headers (headers ). The connection remains active. You can write and receive data in JavaScript, just as you would with the original TCP socket.

Start WebSocket URL by entering ws: // or wss: // (on SSL.

First of all: WebSockets does not have good support in all browsers, and it is clear that IE has slowed down. Therefore, before you plan to use this technology, you must consider the user's use environment. If your project is intended for the Internet or mobile phone-side users, we advise you to think twice.

Second, the requests provided by WebSockets are different from common HTTP requests. It is a full-duplex communication that is always active (if you do not close it ). This means that you don't have to send a request to the server every time you get a response, which saves a lot of resources.

<% @ 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 must use Javascript to write some code (fortunately not complicated ). In addition, some common servers support ws requests. Take Tomcat as an example. In version 6.0, the WebSocketServlet object has been marked as @ java. lang. Deprecated. Versions later than 7.0 support the implementation provided by jsr365, so you must use annotations to complete related 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 ConcurrentLinkedQueue<WebSocket>();private Session session;@OnOpenpublic void onOpen(Session session) {this.session = session;CONNECTIONS.offer(this);}@OnMessagepublic void onMessage(String message) {broadcast(message);}@OnClosepublic void onClose() {CONNECTIONS.remove(this);}private synchronized void broadcast(String msg) {for (WebSocket point : CONNECTIONS) {try {point.session.getBasicRemote().sendText(msg);} catch (IOException e) {CONNECTIONS.remove(point);try {point.session.close();} catch (IOException e1) {}}}}} 

Iii. Summary (from request to push)

In traditional communication solutions, if system A requires information in system B, it will send A request to system B. System B processes the request, and system A waits for the response. After the processing is completed, the response is sent back to system. In synchronous communication mode, resource usage efficiency is relatively low, because processing time is wasted when the response is waited.

In asynchronous mode, system A subscribes to the information it wants to obtain from system B. Then, system A can send A notification to system B or immediately return information. At the same time, system A can process other transactions. This step is optional. In event-driven applications, you generally do not have to request other systems to send events because you do not know what these events are. After system B releases A response, system A immediately receives the response.

In the past, Web frameworks used to rely on the traditional "request-response" mode, which causes page refresh. With the emergence of Ajax, Reverse Ajax, and WebSocket, the concept of the event-driven architecture can now be easily applied to the Web to obtain benefits such as decoupling, scalability, and reactivity. A better user experience will also bring new business opportunities.

The above is a 30-minute master of reverse Ajax introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.