The principle analysis of Web-server push technology and the simple use of dwr frame

Source: Internet
Author: User
Tags glassfish

1 Background

Server Push Technology (serverpushing) is one of the hottest buzzword in recent web technologies. It is followed by "Ajax" after another highly sought after web technology. The recent popularity of "Server Push Technology" has a close relationship with "Ajax".

With the advent of Ajax technology, developers have once again seen the opportunity to use browsers to replace desktop applications, and this opportunity is huge. Ajax changes the entire page refresh into a partial refresh of the page, and the transfer of the data is done asynchronously, which causes the visual differences in the network latency to disappear.

However, there is a fatal flaw in AJAX applications in browsers that cannot meet the needs of traditional desktop systems. That's "server-initiated messaging" (server-initiated message Delivery). In many applications, server software needs to proactively send messages or information to clients. Because the server grasps the main resources of the system, it can get the state change of the system and the occurrence of the event first. When these changes occur, the server needs to proactively send messages to the client in real time. For example, stock changes. There is no problem with this requirement in traditional desktop systems because there is usually a persistent connection between the client and the server, which can pass a variety of data in both directions. Web applications that are based on HTTP protocols are not.

2 How the client gets notified

We know that the Web Access mechanism is inherently designed to pull the data, 1, that is, only allow the browser side to initiate the request, the server is a passive response, does not allow the server to send a connection request to browser, That is, there is no design implementation for the server to Browser push data. Although there is no direct implementation, you can use some workarounds to accomplish similar functions.

2.1 Traditional Polling

In the early days of the web, this was often implemented using meta refreshes. This will automatically instruct the browser to reload the page after a specified number of seconds to support humble polling (polling). For example, add the <meta http-rquiv= "Refresh" Content=12> in the HTML file, which is actually the HTTP header that tells the browser to update the document every 12 seconds.

Advantage : Server-side configuration is not required.

Disadvantages :

A) Bad user experience

b) The pressure on the server, and caused a great waste of bandwidth.

2.2 Ajax Polling

Ajax interval (usually using JavaScript's settimeout function) goes to the server to see if there is a change, so that the incremental update. But how long is the interval to query becomes a problem, because performance and immediacy cause a serious inverse relationship. The interval is too short, and a continuous request can break the server, the interval is too long, and the new data on it takes more time to reach the client.

Advantages:

A) There is no need for too many server-side configurations.

b) Reduce the load on the bandwidth (because the server is not returning a full page).

Disadvantages:

A) There is no noticeable reduction in the pressure on the server.

b) Poor real-time, there is a certain delay.

application: This is a very common technique, for example, where most webmail applications use this technique to display e-mail messages when e-mail arrives.

2.3 Comet

The comet mode is popular as a long connection mechanism (long lived HTTP). The request was also initiated by the browser side, but the server side responded with a seemingly very slow response. So during this period, the server side can use the same connection to send the data to be updated actively to browser. So the request may wait for a long time without any data return, but once the new data is available, it will be sent to the client immediately. There are many different implementations of comet, but in general there is an increase in load on the server side. Although for the unit operation, it is necessary to suggest only one connection at a time, but because connection is maintained for a long time, Server-side resource usage is increased.

Advantages: Good real-time (message delay is small), good performance (can support a large number of users)

disadvantage: long-term occupancy of the connection, loss of the characteristics of high concurrency without state.

Application: stock system, real-time communication.

2.4 Flash XML Socket

The implementation of this scheme is based on: first, Flash provides the Xmlsocket class. Second, JavaScript and flash tightly combined: in JavaScript can directly invoke the Flash program provided by the interface.

Disadvantages:

A) because the Xmlsocket does not have an HTTP tunnel function, the Xmlsocket class cannot automatically pass through the firewall;

b) Because of the use of a socket interface, you need to set up a communication port, firewall, proxy server may also restrict the non-HTTP channel port;

Application: network chat room, network interactive game.

2.5 Java Applet Socket interface

A Java Applet is used on the client side to create a "server Push" through the Java.net.Socket or Java.net.DatagramSocket or java.net.MulticastSocket to establish a socket connection to the server.

Disadvantage: The client is required to install the Java Virtual machine.

3 Comet Introduction

Comet is sometimes also called reverse Ajax or server-side push technology (server-side push). The idea is simple: push data directly from the server to the browser without waiting for the browser to request data. It sounds simple, but if you're familiar with Web applications, especially the HTTP protocol, you'll know that it's never easy. Implementing a comet-style Web application, while guaranteeing scalability on the browser and server, has only been possible in recent years. At present, some major web sites have similar principles, such as: WEBQQ, happy net, school and so on, they are in the news dynamic is similar to the use of technology, but the specific implementation of different ways.

The essence of comet is to use the server and JavaScript to maintain a long browser connection while completing the browser-side response to server-side events. Such an event broadcast mechanism is cross-network, but also real-time.

A server that uses Comet technology makes a persistent connection with the client after a request is made by the client, and the server pushes the packet to the client based on the client's request, which is uninterrupted. The data that is pushed to the client by the server is constantly generating new content on the client's browser and does not produce an HTML document header like the client pull, which greatly reduces the latency and takes a step forward to (server response-client request) synchronization.

Server push is typically more efficient than a client drag because it does not have to establish a new connection for subsequent data. Because the connection is always maintained, even if there is no data transfer, the server must be willing to allocate these TCP/IP ports, which is a serious problem for servers with a limited number of TCP/IP ports.

The client towing efficiency is low because this must establish a new connection for transmitting data each time. But it does not have to remain connected at all times. In practice, establishing an HTTP connection usually takes a considerable amount of time, up to one second or more. As a result of performance considerations, Server push is more attractive to end users, especially in situations where information needs to be updated frequently.

Another advantage of server push relative to client drag is that server push is relatively easy to control. For example, the server maintains a connection every time it pushes, but it can turn off any of the connections at any time without having to set up a special algorithm on the server. And the client drag in the same situation is a lot of trouble, it every time to establish a connection with the server, the server in order to handle the client pull request and a specific end-user matching, and so on, need to use a rather cumbersome algorithm.

As mentioned above, in a server push, connections are always maintained in multiple responses, allowing the server to send more data at any time. One obvious benefit is that the server is fully capable of controlling the time and frequency of updating data. In addition, this method is highly efficient because it is always kept connected. The disadvantage is that keeping the connection state wastes server-side resources. Server Push-back is relatively easy to interrupt.

4 Comet Implementation (Java language)

4.1 Dead Circulation method

The simplest nature is the dead-loop method, which can further improve performance if the observer pattern is used.

However, the disadvantage of this approach is that after the client requests the servlet, the Web server opens a thread to execute the servlet's code, and the servlet will not end, causing the thread to be freed. Thus, a client is a thread, and when the number of clients increases, the server still bears a heavy burden.

4.2 overwriting a Web server

The current trend is to start from within the Web server, with NIO (JDK 1.4 proposed Java.nio package) rewrite the implementation of Request/response, and then use the thread pool to enhance the resource utilization of the server, so as to solve this problem, currently support this non-EE official technology Services Glassfish and Jetty.

The most notable new feature of JDK version 1.4 (including later versions) is the addition of NIO (new IO), which can handle network requests in a non-blocking manner, which makes it possible to handle a large number of concurrent requests in Java with a small number of threads.

Jetty 6 is designed to handle a large number of concurrent connections, using the Java-language non-clogging I/O (Java.nio) library and using an optimized output buffering architecture. Jetty also has a killer that handles long connections: A feature called continuations.

Grizzly as a very important project in GlassFish, is to use NIO technology to implement the high-performance Java-only HTTP engine in the application server. Grizzly is also a GlassFish-independent framework that can be used to extend and build its own server software.

Features: The use of NIO is not a simple technique, and some of its features make programming models more complex than previously blocked.

4.3 using frames

The Java-based mature server push framework has DWR.

DWR is an open source solution that uses the Apache licensing protocol, which contains a server-side Java library, a DWR servlet, and a JavaScript library. While DWR is not the only AJAX-RPC toolkit available on the Java platform, it is the most mature and offers many useful features. From the simplest point of view, DWR is an engine that exposes the methods of server-side Java objects to JavaScript code. Using DWR effectively removes all of the AJAX request-response loops from your application code. This means that the client code no longer needs to deal directly with the XMLHttpRequest object or the server's response. You no longer need to write the object's serialization code or use a third-party tool to turn the object into XML. It is not even necessary to write the servlet code to adjust the AJAX request to a call to a Java domain object.

DWR has added push functionality starting from 2.0, which is the ability to send data from the Web-server side to Browser in the case of asynchronous transmissions

A simple DWR push program

The first step is to import the DWR-related jar package into the project

Step two Configure the Web. xml file

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://java.sun.com/xml/ns/javaeehttp ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><servlet><servlet-name>dwr-invoker</ servlet-name><servlet-class>org.directwebremoting.servlet.dwrservlet</servlet-class><!-- Sets whether to allow the use of DWR push technology--><init-param><param-name>activereverseajaxenabled</param-name>< Param-value>true</param-value></init-param><init-param><param-name> maxwaitafterwrite</param-name><param-value>-1</param-value></init-param>< Load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name> dwr-invoker</servlet-name><url-pattern>/dwr/*</url-pattern></servlet-mapping></ Web-app>

The third step is to write the Com.im.service.SendPushService class

public class Sendpushservice {//Send message public void Send (String msg) {System.out.println ("========== called Send Method ==========") ; Scriptbuffer Scriptbuffer = new Scriptbuffer (); Construct JS script Webcontext webcontext=webcontextfactory.get (); Scriptsession myscsession = Webcontext.getscriptsession (); Scriptbuffer.appendscript ("Dwrtest ("); Scriptbuffer.appenddata (msg); Scriptbuffer.appendscript (")"); Util Util = new Util (myscsession); Util.addscript (Scriptbuffer); Push message to Client}}

The fourth step defines the outward exposed interface in the Dwr.xml file

<allow><create creator= "new" javascript= "Sendpushservice" ><param Name= "class" value= " Com.im.service.SendPushService "/></create></allow>

Fifth step: Writing a JSP file

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

WebSocket
Features in the HTML5
Introduction: A full duplex bidirectional communication technology, the main purpose is to provide a two-way, TCP scoket-like and persistent stateful communication between Web browsers and Web servers. It is accessed through the API provided inside the browser. The low version of the browser does not websocket this standard.
Compatibility: FireFox 4.0+, Chrome 4.0+, Safari 5.0+. Internet Explorer is not supported at this time
PS: Online examples of websocket are mostly chat rooms. In the past, the use of chat rooms in the web was often a polling method,
That is, every once in a while to pull some data from the service side. While there are technologies such as Comet Bigpipe, the essence is still "pull" rather than "push" on the server. With the WebSocket, the service-side push is very well implemented.

 

 

Web-side server push Technology principle analysis and DWR framework simple use reprint

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.