Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of reverse Ajax

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "reverse Ajax example analysis", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn the "reverse Ajax example analysis" this article.

Scenario 1: when there is a new message, the web page automatically pops up a prompt without the need for the user to manually refresh the inbox.

Scenario 2: when the user's mobile phone scans the QR code in the page, the page will jump automatically.

Scenario 3: if anyone speaks in an environment similar to a chat room, all logged-in users can see the message immediately.

Compared with the traditional MVC model request that must be initiated from the client and responded by the server, using reverse Ajax can simulate the server to actively push events to the client and improve the 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, but the applications in Struts2 or SpringMVC are not involved. In addition, the configuration of Servlet is also annotated, and you can refer to other materials for related knowledge.

1. Comet (the best means of compatibility)

Comet is essentially the concept of being able to send data from the server to the client. In a standard HTTP Ajax request, the data is sent to the server, and the reverse Ajax simulates an Ajax request in certain ways, so that the server can send events to the client as quickly as possible. Because ordinary HTTP requests are often accompanied by page jumps, and push events require browsers to stay under the same page or framework, the implementation of Comet 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 takes 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 that needs to be pushed arrives, the server traverses the request in the container and deletes it after returning the reply. Then all browsers that stay on the page will get the reply and send the Ajax request again, repeating the above process.

WebSocket$ (function () {connect (); $("# btn") .click (function () {var value = $("# message"). Val (); $.ajax ({url: "longpolling?method=onMessage&msg=" + value,cache: false,dataType: "text", success: function (data) {}); function connect () {$.ajax ({url: "longpolling?method=onOpen", cache: false,dataType: "text", success: function (data) {connect () Alert (data);}});} LongPolling

We notice that requests sent by btn do not really need to get a reply. The key to the whole process is the need for the client to always keep the server holding the request for connect (). The server first needs to support this asynchronous response. Fortunately, most of the Servlet containers have provided good support so far. Take 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 CONNECTIONS = new ConcurrentLinkedQueue () @ 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 ();}

ConcurrentLinkedQueue is a thread-safe implementation of the Queue queue, which is used here as a container for storing requests. AsyncContext is an asynchronous environment supported by Tomcat, and different servers use slightly different objects. The object supported by Jetty is Continuation. The request that has completed the broadcast needs to be terminated by context.complete () and deleted using CONNECTIONS.remove (context).

2. WebSocket (support from HTML5)

Comet using HTTP long polling is the best way to implement reverse Ajax reliably, because all browsers now provide this support.

WebSockets appears in HTML5 and is a newer reverse Ajax technology than Comet. WebSockets supports two-way, full-duplex communication channels, and many browsers (Firefox, Google Chrome, and Safari) also support it. Connections are made through HTTP requests (also known as WebSockets handshakes) and some special headers (header). The connection is always active, and you can write and receive data in JavaScript, just as you use the original TCP socket.

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

First of all: WebSockets doesn't have good support on all browsers, and obviously IE is holding you back. Therefore, you must consider the user's environment before you plan to use this technology, and if your project is aimed at the Internet or including mobile users, please think twice.

Second: the request provided by WebSockets is different from a normal HTTP request, it is a full-duplex communication and is always active (if you don't turn it off). This means that you don't have to send a request to the server every time you get a reply, which saves a lot of resources.

WebSocket$ (function () {var websocket = null;if ("WebSocket" in window) {websocket = new WebSocket ("websocket");} else {alert ("not support");} websocket.onopen = function (evt) {} websocket.onmessage = function (evt) {alert (evt.data);} websocket.onclose = function (evt) {} $("# btn") .click (function () {var text = $("# message"). Val (); websocket.send (text);}); WebSocket;

JQuery doesn't have better support for WebSocket yet, so we have to use Javascript to write some of the code (fortunately, it's not complicated). And some common servers can support ws requests, take Tomcat as an example. In version 6. 0, the WebSocketServlet object has been marked as @ java.lang.Deprecated,7.0. Later versions support the implementation provided by jsr365, 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 CONNECTIONS = new ConcurrentLinkedQueue (); 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 schemes, if system A needs information from system B, it sends a request to system B. System B will process the request, and system A will wait for a response. When the processing is complete, the response is sent back to system A. In synchronous communication mode, the use of resources is inefficient because processing time is wasted while waiting for a response.

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

Web frameworks used to rely on the traditional "request-response" pattern, which led to page refreshes. With the advent of Ajax, Reverse Ajax, and WebSocket, the concept of event-driven architecture can now be easily applied to Web for the benefits of decoupling, scalability, and reactivity. A better user experience will also bring new business opportunities.

The above is all the contents of this article "sample Analysis of reverse Ajax". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report