Analysis of Web server push technology principles and simple use of the dwr framework, dwr framework

Source: Internet
Author: User
Tags object serialization glassfish

Analysis of Web server push technology principles and simple use of the dwr framework, dwr framework

1. Background
ServerPushing is one of the most popular Web technologies recently. It is another popular Web technology after "Ajax. The recent popularity of "server push technology" is closely related to "Ajax.
With the rise of Ajax technology, developers once again saw the opportunity to use browsers to replace desktop applications. Ajax changes the whole page to partial page refresh, and the data is transmitted asynchronously, which causes the visual difference caused by network latency to disappear.
However, there is a fatal defect in Ajax applications in browsers that cannot meet the needs of traditional desktop systems. That is, Server-Initiated Message Delivery ). In many applications, server software must send messages or messages to clients. Because the server has mastered the main resources of the system, it can first obtain the state changes and events of the system. When these changes occur, the server needs to actively send messages to the client in real time. For example, stock changes. In traditional desktop systems, there is no problem because there is usually a persistent connection between the client and the server. This connection can transmit various data in two directions. However, HTTP-based Web applications do not work.
2. The client is notified.
Figure 1 traditional web Access Mechanism
We know that the Web access mechanism is designed for pull data by nature. 1, that is, only the Browser can actively initiate requests, and the server is passively responding, the Server is not allowed to send a connection request to the Browser, that is, it does not provide design implementation for the server to push data to the Browser. although there is no direct implementation method, some flexible methods can be used to complete similar functions.
2.1 Traditional round robin
In the early days of the Web, meta Refresh was often used. This will automatically instruct the browser to re-load the page after a specified number of seconds, so as to support simple round robin (polling ). For example, adding <META HTTP-RQUIV = "Refresh" CONTENT = 12> to an HTML file is actually an HTTP header that notifies the browser to update the document every 12 seconds.
Advantage: No server configuration is required.
Disadvantages:
A) Poor User Experience
B) the pressure on the server is high and the bandwidth is greatly wasted.
2.2 Ajax round robin
Ajax queries the server to see if there is any change after a period of time (usually using the setTimeout Function of JavaScript) to perform incremental updates. However, the interval between queries becomes a problem, because the performance and real-time result in a serious inverse relationship. If the interval is too short, continuous requests will crash the server. If the interval is too long, the more time the new data on the server needs to arrive at the client.
Advantages:
A) Too many server configurations are not required.
B) Reduce the bandwidth load (because the server does not return a full page ).
Disadvantages:
A) There is no significant reduction in the pressure on servers.
B) poor real-time performance with a certain latency.
Application: This is a very common technology. For example, most webmail applications use this technology to display emails when an email arrives.
2.3 Comet
In general, the Comet method is a persistent connection mechanism (long lived http ). In the same way, the Browser initiates a request, but the Server provides a very slow response. In this way, the server can use the same connection to actively send the data to the Browser during this period. Therefore, the request may wait for a long time, during which no data is returned, but once new data is generated, it will be immediately sent to the client. Comet has many implementation methods, but in general, the Server load will increase. although only one connection is recommended for a unit operation, the resource usage on the server is increased because the connection is maintained for a long time.
Advantages: good real-time performance (low message latency) and good performance (supporting a large number of users)
Disadvantage: the connection is used for a long time and the high concurrency is lost.
Application: Stock System and real-time communication.
2.4 Flash XML Socket
The basis of this solution is: 1. Flash provides the XMLSocket class. Ii. Close Combination of JavaScript and Flash: In JavaScript, you can directly call the interfaces provided by the Flash program.
Disadvantages:
A) Because XMLSocket does not have the HTTP tunnel function, the XMLSocket class cannot automatically pass through the firewall;
B) because an interface is used, you need to set a communication port. Firewall and proxy servers may also restrict non-HTTP Channel ports;
Applications: online chat rooms and online interactive games.
2.5 Java Applet set Interface
Using a Java Applet on the client, you can use java.net. Socket, java.net. DatagramSocket, or java.net. MulticastSocket to establish a connection with the Socket interface on the server to implement "server push ".
Disadvantage: the Java Virtual Machine needs to be installed on the client.
3. Introduction to Comet
Comet is sometimes called reverse Ajax or 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 are familiar with Web applications, especially HTTP, you will know that this is not simple. Implementing Comet Web applications and ensuring scalability on browsers and servers is only possible in recent years. At present, some mainstream websites have similar principles, such as webQQ, kaixin.com, and on-campus websites. The message dynamics in these websites all adopt similar technologies, but the specific implementation methods are different.
The essence of COMET is to use the server and javascript to maintain the browser's persistent connection and complete the browser-side response to server-side events. Such an event broadcast mechanism is cross-network and real-time.
A server using the Comet technology establishes a permanent connection with the client after the client makes a request, and then the server will continuously push data packets to the customer according to the client's requests, this push process is uninterrupted. The data pushed from the server to the Client will continuously generate new content in the Client's browser, and will not generate HTML document headers like Client pull, thus greatly reducing the delay time, it is a step forward to (server response-client request) synchronization.
Server push is generally more efficient than client drag because it does not have to create new connections for subsequent data. Because the connection is always maintained, even if there is no data transmission, the server must be willing to allocate these TCP/IP ports, this is a serious problem for servers with a limited number of TCP/IP ports.
Client drag efficiency is low, because this must create a new connection for each data transfer. However, it does not have to always maintain the connection. In practice, it usually takes a considerable amount of time to establish an HTTP connection, as many as one second or even more. Therefore, in terms of performance, server push is more attractive to end users, especially when information needs to be updated frequently.
Another advantage of server push over client dragging is that server push is relatively easy to control. For example, the server maintains a connection for each push, but it can close any connection at any time without setting special algorithms on the server. In the same situation, client dragging requires a lot of trouble. It needs to establish a connection with the server every time, and the server matches the client dragging request with a specific end user in order to process the situation, requires a very troublesome algorithm.
As mentioned above, connections are always maintained among multiple responses in server push so that the server can send more data at any time. One obvious benefit is that the server can fully control the time and frequency of data update. In addition, this method is highly efficient because the connection is always maintained. The disadvantage is that maintaining the connection will waste resources on the server. Server push is easy to interrupt.
4. Comet implementation (Java language)
4.1 Infinite Loop Method
The simplest method is the infinite loop method. If the observer mode is used, the performance can be further improved.
However, the disadvantage of this approach is that after the client requests this servlet, the web server will enable a thread to execute the servlet code, and the servlet will not end, resulting in the thread cannot be released. Therefore, when the number of clients increases, the server will still bear a lot of burden.
4.2 rewrite the web Server
The current trend is to start with the internal web server, using nio (java. nio package) rewrite the request/response implementation, and use the thread pool to enhance the server's resource utilization, so as to solve this problem. Currently, the servers that support this unofficial J2EE technology include Glassfish and Jetty.
The most significant New feature of JDK 1.4 (including later versions) is the addition of NIO (New IO), which can process network requests in a non-blocking manner, this allows Java to process a large number of concurrent requests with only a small number of threads.
Jetty 6 is designed to handle a large number of concurrent connections. It uses the Java language's I/O (java. nio) Library and uses an optimized output buffer architecture. Jetty also has a killer for handling persistent connections: A feature called Continuations.
Grizzly is a very important project in GlassFish. It uses NIO technology to implement a high-performance pure Java HTTP engine in the application server. Grizzly is also a framework structure independent of GlassFish and can be used separately to expand and build your own server software.
Features: NIO is not a simple technique. Some of its features make programming models more complex than the original blocking method.
4.3 framework
Java-based mature server push frameworks include DWR.
DWR is an open-source solution using the Apache license protocol. It contains the server-side Java library, a DWR servlet, and a JavaScript library. Although DWR is not the only available Ajax-RPC toolkit on the Java platform, it is the most mature and provides many useful functions. From the simplest point of view, DWR is an engine that can expose methods of server-side Java objects to JavaScript code. Using DWR can effectively eliminate all Ajax request-response loops from application code. This means that the client Code no longer needs to directly process the XMLHttpRequest object or server response. You no longer need to compile Object serialization code or use a third-party tool to convert an object into XML. You do not even need to write servlet code to adjust Ajax requests to call Java domain objects.
DWR has added the push function since 2.0, that is, it can send data from the Web-Server to the Browser during asynchronous transmission.
A simple dwr push Program
Step 1 import jar packages related to dwr to the Project
Step 2 configure the web. xml file
[Html] view plaincopy
<? 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/javaee
Http://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>
<! -- Set whether dwr push technology is allowed -->
<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>
Step 3: Compile the com. im. service. SendPushService class
[Java] view plaincopy
Public class SendPushService {
// Send a message
Public void send (String msg ){
System. out. println ("=========== the send method is called ======== ");
ScriptBuffer scriptBuffer = new ScriptBuffer (); // construct a 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 messages to the client
}
}
Step 4 define the externally exposed interface in the dwr. xml file
[Html] view plaincopy
<Allow>
<Create creator = "new" javascript = "SendPushService">
<Param name = "class" value = "com. im. service. SendPushService"/>
</Create>
</Allow>
Step 5: compile a jsp file.
[Html] view plaincopy
<% @ 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">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Base href = "$ {basePath}"/>
<Script type = 'text/javascript 'src = '$ {basePath} dwr/engine. js'> </script>
<Script type = 'text/javascript 'src = '$ {basePath} dwr/util. js'> </script>
<Script type = 'text/javascript 'src = '$ {basePath} dwr/interface/SendPushService. js'> </script>
<Script type = "text/javascript">
Function hello (){
SendPushService. send ("first dwr push program ");
}
/** Dwr calls this method in the background **/
Function dwrtest (data ){
Alert (data );
}
</Script>
<Title> the first dwr push Program </title>
</Head>
<Body onload = "dwr. engine. setActiveReverseAjax (true);">
<Input type = "button" value = "click" onclick = "hello ();"/>
</Body>
</Html>

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.