Detailed analysis and examples of Push Technology Based on dwr2.0

Source: Internet
Author: User

DWR has added the push function since 2.0, that is, it can send data from the web-server end
Browser.
We know that the Web access mechanism is designed for pull data by nature, that is, it only allows the browser to actively initiate requests.
Is a passive response. The server is not allowed to send a connection request to the browser, that is, the server does not send a connection request to the browser
Push data provides design implementation.
Although there is no direct implementation method, some flexible methods can be used to accomplish similar functions:
1. Polling
Polling is actually a round-robin. It uses browser to repeatedly send requests to the server at a relatively short interval. However
After updating the page, there is nothing new about this method, but you only need to do some work on the browser side, even if there is not much server-side configuration
No problem. The round-robin method will generate different levels of additional load for the server based on different access intervals, because each access
The connection is re-established.
2. Comet
In general, the comet method is a persistent connection mechanism (long lived HTTP). It is also initiated by the browser client.
However, the server provides a very slow response. In this way, the server can use the same
Connection sends the data to be updated to browser. Comet in many ways.
The server load will increase. Although for the unit operation, you only need to recommend one connection at a time, but because the connection is
For a long period of time, the occupation of server resources is increased.
3. Piggyback
Piggyback is a semi-active method, that is, the browser sends the request, but each request
In addition to the current response, the system also sends the changes that have occurred since the previous request to browser.
The requested update will be carried to the response of the next request in a concurrent response. In this way, the browser feels like the last request has a more
New. But this feeling depends on the frequency of browser requests to the server. If the second request is delayed, then the last
Will not be obtained.
In dwr2.0, active and passive modes can be used. Here we mainly discuss
Active (active) mode. Active (active) mode is divided into the following three types:
• Full streaming mode
• Early closing Mode
• Polling Mode
Full streaming mode
This is a default configuration in active mode, with a fast response speed, and the established link only checks the token every 60 seconds.
Whether the browser is active or not. The configuration of this working mode is very simple. When configuring DWR in Web. XML, add the following content:

<servlet><servlet-name>dwr-invoker</servlet-name><servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class><init-param><param-name>activeReverseAjaxEnabled</param-name><param-value>true</param-value></init-param></servlet>

Then add the following sentence to the browser page:

DWR. Engine. setactivereverseajax (true );

It should be noted that long links will increase the resource occupation of the server. Some servers, such as jetty, allow thread shutdown on the client.

(Connection) in the new version, this capability will be extended to glassfish and tomcat. In short, the dominant idea of DWR is

Server to reduce the load.

Early closing Mode

If there is a proxy or mod_jk between browser and server, you need to be able to work well. This mode is required:

Mode is similar to full streaming mode. Connection is enabled in full mode. However, if no output is available,

It will close the connection in a configured time, usually 60 seconds.

From version 2.04, DWR uses early closing mode by default. To use full streaming mode, you must

Perform the following Configuration:

<init-param><param-name>maxWaitAfterWrite</param-name><param-value>-1</param-value></init-param>

Set maxwaitafterwrite to-1, indicating that the time is the same as that of full streaming mode. Set the closing time to 60.

Seconds.

Polling Mode

Polling mode is a polling method, which can avoid occupying server resources due to persistent connection.

In the round-robin mode, you also need to configure the following:

<init-param><param-name>org.directwebremoting.extend.ServerLoadMonitor</param-name><param-value>org.directwebremoting.impl.PollingServerLoadMonitor</param-value></init-param>
<init-param><param-name>disconnectedTime</param-name><param-value>60000</param-value></init-param>

This is to change the polling cycle to 6000 milliseconds, that is, 6 seconds.

The Web has the push method, which is a dream of many applications. For example, if there is a web-based network chat system,
If the push technology is used, it can better meet the functional requirements. For example, the server needs to actively forward
The browser needs such functions to send data to applications.
The following is an example of a stock offer, which allows the server to actively send stock information to the browser.

First let's talk about the required jar package: DWR. Jar commons-logging.jar
Then we will introduce how to configure:
1. Configure the following content in Web. xml:

<servlet><servlet-name>dwr-invoker</servlet-name><servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class><init-param><param-name>activeReverseAjaxEnabled</param-name><param-value>true</param-value></init-param></servlet><servlet-mapping><servlet-name>dwr-invoker</servlet-name><url-pattern>/dwr/*</url-pattern></servlet-mapping>

2. Configure the following content in DWR. xml:

<dwr><allow><!-- Reverse Ajax Stock push Demo Config --><create creator="new" javascript="StocksPusher"><param name="class" value="dwr.reverse.StocksPusher"/></create></allow></dwr>

3. Page of the stock report getstockinfo.html

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> 

4. The main program stockspusher. Java for the offer. The key part is the Chinese comment behind the code.

Package DWR. reverse; import Java. util. arraylist; import Java. util. collection; import Java. util. list; import Org. directwebremoting. webcontext; import Org. directwebremoting. webcontextfactory; import Org. directwebremoting. proxy. DWR. util; import Org. directwebremoting. util. logger;/*** reverse Ajax class. ** @ author Henry Huang */public class stockspusher {Private Static Boolean closemarket = false;/*** initialize the stocklist with values. */Public stockspusher () {}/ *** send the stock-values to the file "getstockinfo.html" */Public void sendstocks () throws interruptedexception {webcontext wctx = webcontextfactory. get (); // obtain the webcontext context string currentpage = wctx. getcurrentpage (); // obtain the current page from the context. These are the required methods for dwrreverse ajax to collect sessions = wctx. getscriptsessionsbypage (currentpage); // multiple scriptsessions may exist in another page. util utilall = new util (sessions); // util is where DWR simulates Brower DWR on the server. util. JS class, engine is also while (true) {thread. sleep (500); If (closemarket) break; stocksbean stock = stockpricetracer. getnextstockinfo (); utilall. setvalue (stock. getstock (), stock. getvalue (); // setvalue () usage and DWR. util. the setvalue () function in JS is used exactly the same. The first parameter is the ID of the page element, and the second parameter is the new value system assigned to the ID. out. println ("pushing stock:" + stock. getstock () + "=" + stock. getvalue () ;}} public void beginshow () {closemarket = false;} public void closeshow () {closemarket = true ;}}

5. Another class is to simulate the stockpricetracer. Java tool that obtains stock information in real time, or to access the database,

It may also come to the satellite's dashboard data, etc. This category uses a random method to get the stock price:

package dwr.reverse;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Stack;/*** Reverse Ajax class.** @author Henry Huang*/public class StockPriceTracer {private static StockPriceTracer tracer = null;private List<StocksBean> stocks = new ArrayList<StocksBean>();private Stack<StocksBean> cycleStack = new Stack<StocksBean>();private StockPriceTracer(){stocks.add(new StocksBean("zsy", "36.55"));stocks.add(new StocksBean("dlsd", "91.01"));stocks.add(new StocksBean("zsh", "22.59"));stocks.add(new StocksBean("lggf", "5.07"));stocks.add(new StocksBean("hedq", "71.77"));stocks.add(new StocksBean("jdsn", "31.61"));stocks.add(new StocksBean("yyrj", "51.29"));stocks.add(new StocksBean("zsyh", "52.70"));stocks.add(new StocksBean("zgtj", "16.96"));stocks.add(new StocksBean("sfz", "54.34"));stocks.add(new StocksBean("jsrj", "178.48"));stocks.add(new StocksBean("zyd", "134.48"));stocks.add(new StocksBean("jzg", "76.32"));stocks.add(new StocksBean("zgpa", "80.63"));stocks.add(new StocksBean("gsyh", "18.79"));stocks.add(new StocksBean("aggf", "20.19"));stocks.add(new StocksBean("zght", "11.13"));}public static StocksBean getNextStockInfo(){if(null == tracer) tracer = new StockPriceTracer();if(tracer.cycleStack.empty()) tracer.cycleStack.addAll(tracer.stocks);StocksBean tmp = tracer.cycleStack.pop();tmp.setValue(tracer.getRandomPrice(tmp.getValue()));return tmp;}private String getRandomPrice(String current){float fcurrent = 0.0F;try{fcurrent = Float.parseFloat(current);}catch(NumberFormatException e){fcurrent = 0.01F;}Random rdm = new Random();float tmp = fcurrent + rdm.nextFloat();return String.valueOf(tmp);}}

6. Another class is a javabeanstockbean. Java

package dwr.reverse;public class StocksBean {private String stock = "";private String value = "";public StocksBean(String stock, String value) {this.setStock(stock);this.setValue(value);}public String getStock() {return stock;}public void setStock(String stock) {this.stock = stock;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}}

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.