Getting started with Comet and the simplest Java Demo

Source: Internet
Author: User
Tags html comment

Getting started with Comet and the simplest Java Demo

How can I receive new messages when I browse the Web page? The HTTP Protocol cannot be used by the server to send messages to the client.

1. Weibo and Forum posts. What should I do if I want to see the latest information? F5 refresh and it will be OK!

2. The above method is passive. If you do not refresh the page, you will not be able to see the message. One way for the server to actively push messages to the client browser is to use setInterval to regularly refresh Ajax.

In this way, the refresh operation is not performed by the user, but is automatically initiated by the browser. the user cannot notice that the server actively pushes messages to the user.

In fact, this method is very simple and practical. The server does not need to perform special processing on such requests (the Comet method requires special processing by the server), so it is often used.

However, for some message notifications, real-time is very important. For example, a game can be hacked several times in a second or even taken away directly. Another example is that in Shaolin football, the number of people in a second is about 100,000.

In this way, if a message is pushed, the server cannot immediately notify the client. You must wait until the next Ajax request is sent to the client. The question is: How much is the interval between two requests. The set interval is too short. HTTP requests always occupy the network speed and performance of the client and server. The interval is too long and client message notifications are not timely.

For some website notifications, people may receive a message in a day or two. If the background is refreshed regularly, it is a waste of resources.

3. Games, chat rooms, stocks, and other applications that often use server push usually use Comet. Comet is actually an HTTP persistent connection, which is a little different from normal HTTP. A common HTTP connection is a request sent by a client, and the server immediately responds and closes the connection immediately. The Comet client sends an HTTP request, and the server does not immediately give a response, but blocks it until a message needs to be sent to the client.

The server does not return a response immediately. This usually happens when the network speed is poor or the server performance is poor, that is, the browser opens a webpage and turns around for a long time. Comet is similar to this one, but it is not caused by poor network speed or poor server performance, but by the server deliberately waiting.

 

Comet has the following implementation methods:

1. long-polling (long-polling)

JS is used to send Ajax requests, but the server does not immediately respond until a message is sent to the client. After the response is complete, the connection is closed. The client immediately sends the request again and waits for the response.

Below is a DEMO:

Front-end page:

 

 <Script type = text/javascript> function getMsg () {// The request address is the URL corresponding to CometServlet. Add a random value parameter to prevent cache problems. var url = comet +? T = + Math. random (); var request = new XMLHttpRequest (); request. onreadystatechange = function () {if (request. readyState = 4) {if (request. status = 200) {if (request. responseText) {// append it to the document in HTML. body. innerHTML + = request. responseText; }}// after Ajax is complete, call Ajax again to request getMsg () ;}}; request. open (GET, url, true); request. send ();} window. onload = getMsg; </script> background Servlet: 

 

 

Public class CometServlet extends HttpServlet {@ Overridepublic void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException {// Thread is used here. sleep to simulate comet, which is equivalent to pushing a message to the client every five seconds. try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} PrintWriter out = response. getWriter (); out. println (helloworld );}}
Open the html page in the browser and you can see that the server pushes a helloworld string to the client every five seconds. When the string HTTP connection is received, Ajax immediately sends a request waiting for the next response from the server.

 

2. streaming)

Unlike the long-polling above, the server does not close the connection after sending the message, but keeps the HTTP connection waiting for the next message. In this way, the client does not need to request a message again after the message connection is closed.

This method is based on a Header in the HTTP Response Header: Transfer-Encoding: chunked. In the normal HTTP Response Header, Content-Length indicates the size of the entire response in bytes. the browser receives all the response data before loading the Content. When Transfer-Encoding is set: After chunked is set, the response size is not fixed, and the browser loads a little response data.

The stream-based Comet background implementation is the same, but there are several different front-end methods:

2.1 iframe stream

One front-end Implementation Method of streaming-based Comet is to add a hidden iframe to HTML, and set the src of iframe to the address of CometServlet. If the server has a new message, it will write a script tag to this iframe, which contains a piece of Javascript. After the browser loads the Javascript code, it will run the JS script and control the addition of HTML through the JS Code.

Front-end page:

 

 <Script type = text/javascript> // append a message to HTML. This function calls function addMsg (msg) {var msgElement = document to the javascript script added to iframe. getElementById (msg); msgElement. innerHTML + = msg ;}</script> <Iframe id = "iframe" src = "comet" style = "display:"> </iframe> 

 

Backend Servlet:

 

Public class CometServlet extends HttpServlet {@ Overridepublic void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException {PrintWriter out = response. getWriter (); // the received data is not immediately output to the page due to browser reasons (Chrome is normal for FireFox and IE. Enter a string with a length greater than 1024. StringBuilder sb = new StringBuilder (); for (int I = 0; I <1024; I ++) {sb. append ('A');} out. println (
 ); // Add the HTML comment out. flush (); while (true) {// Use Thread here. sleep to simulate comet, which is equivalent to pushing a message to the client every five seconds. try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} // write a js file to iframe every five seconds, call the addMsg function of parent, and add content out to HTML. println (<script> parent. addMsg ('helloworld'
') </Script>); out. flush (); // flush is required here; otherwise, data is not sent }}}
During the test, I found that FireFox and IE Browsers Do not load the server's response immediately. The browser has a cache and will load the server only when it reaches a certain size. According to the test, FireFox is 1024 bytes. Therefore, before pushing a message to the Servlet, I first write a string greater than 1024 bytes to the response to avoid the problem of loading the browser in time. Chrome does not have this problem.

 

A small problem with the iframe-based stream mode is that, because the iframe has not been fully loaded and is in the connection state, the progress of all browsers will remain incomplete, that is, it is always in a circle.

2.2 FireFox

In FireFox, when the readyState of Ajax is set to 3, request. responseText is obtained. That is, partial response data can be obtained for incomplete requests. This method is not supported by other browsers such as IE.

Front-end page:

 

 <Script type = text/javascript> function getMsg () {// The request address is the URL corresponding to CometServlet. Add a random value parameter to prevent cache problems. var url = comet +? T = + Math. random (); var request = new XMLHttpRequest (); request. onreadystatechange = function () {if (request. readyState = 3) {if (request. responseText) {// note that HTML is no longer appended here, And responseText contains all previous message documents. body. innerHTML = request. responseText ;}}; request. open (GET, url, true); request. send ();} window. onload = getMsg; </script> background Servlet: 

 

 

Public class CometServlet extends HttpServlet {@ Overridepublic void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException {PrintWriter out = response. getWriter (); while (true) {// Use Thread here. sleep to simulate comet, which is equivalent to pushing a message to the client every five seconds. try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} out. println (helloworld); out. flush (); // flush is required here; otherwise, data is not sent }}}


 

Finally, the background Java code in this article is only used to learn and demonstrate Comet, which is not actually usable. The background is just a simple sleep without any function. Because Comet uses HTTP persistent connections, when the client is closed, the server is still blocked and the Servlet is not stopped, which is very dangerous. Tomcat and Jetty all have mature solutions for Comet technology. I will continue to introduce them in the following blog posts.

 

 

 

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.