Introduction to Comet and the simplest Java Demo

Source: Internet
Author: User
Tags script tag

When browsing the Web page, suppose there is a new message, how to receive it? The HTTP protocol cannot be actively sent by the server to the client.

1, Brush micro Bo, visit the forum bar, want to see the latest information how to do? F5 refresh a bit ok!

2, the above one way is passive, assuming the user does not go to refresh the page, will not see the message. How to let the server actively push the message to the client browser, one way is to use setinterval Ajax timed refresh.

So. The refresh operation is not performed by the user. Instead, the browser is the one who initiates the request. Users can not be aware that the user's feeling is that the server actively push the message to the user.

In fact, such a way is very easy and very useful. The server does not have to do special processing for such requests (the Comet method requires server special processing). So it is often used.


However, for some message notifications, real-time is very important. For example, games. A second can cut several knives or even be taken away directly. For example, the Star Ye "Shaolin Football", the people in a second hundreds of thousands of up and down.



The message is pushed in such a way. The server has a message that cannot be immediately notified to the client. You have to wait until the next AJAX request ability is returned to the client. So the question is: How much is the interval of two requests to be set to fit.

The set-up interval is too short to always make HTTP requests for client and server speed and performance. The interval time is long, the client message notification is not timely.


And for some site message notification, people may be able to receive a message a day or two. Then the background has been timed to refresh the words are also white brush. Waste of resources.

3, games, chat rooms, stocks and so often used in the server push application. Comet is usually used. Comet is actually an HTTP long connection, which is a bit different from normal HTTP. The normal HTTP connection is that the client sends a request, the server responds immediately, and the connection shuts down immediately. And comet is the client making an HTTP request. The server does not respond immediately. Instead, the response is blocked until a message needs to be sent to the client.

The server does not return a response immediately, which usually occurs when the network speed is poor or the server performance is poor. That is, the browser opens a webpage and turns the circle for a long time. Comet is similar to this. However, it is not a bad speed or poor server performance caused by the server is good to wait.


There are several ways to implement Comet:

1. Long polling (long-polling)

Use JS to send AJAX requests, but the server will not respond immediately, until the server has a message to the client to respond, after the completion of the connection closed, the client immediately send the request again, waiting for a response.

Here is a demo:

Front page:

<! DOCTYPE html>
Background servlet:

public class Cometservlet extends HttpServlet {@Overridepublic void doget (HttpServletRequest request, HttpServletResponse response) throws IOException {//here with Thread.Sleep to simulate comet, equivalent to every 5 seconds the server pushes a message to the client try { Thread.Sleep (5000);} catch (Interruptedexception e) {e.printstacktrace ();} PrintWriter out = Response.getwriter (); Out.println ("helloworld<br>");}}
Open the HTML page in the browser. Be able to see the server pushing a HelloWorld string to the client every 5 seconds. The incoming string HTTP connection is disconnected. Ajax then makes a request to wait for the next response from the server.


2, stream (streaming)

Unlike the long-polling above. When the server finishes the message, it does not close the connection, but instead keeps the HTTP connection waiting for the next message.

This way, the client does not have to request again every time the message connection is received.

The principle of this approach is a header:transfer-encoding:chunked of the HTTP protocol response header.

In a normal HTTP response header, content-length indicates the byte size of the entire response, and the browser receives all the response data before the content is loaded.

When the transfer-encoding:chunked is set, the response size is not fixed, and the browser receives a little response data and loads it.

The stream-based comet background implementation is the same, but there are several different ways the front end will be:

2.1. IFRAME Stream

One of the front-end implementations of streaming-based comet is to add a hidden iframe,iframe src setting to the Cometservlet address in HTML. When the server has a new message, it writes a script tag into the IFRAME. Including a piece of JavaScript, the browser loaded complete JS will be executed JS script, through the JS code to control the addition of HTML.

Front page:

<! DOCTYPE html>

Background servlet:

public class Cometservlet extends HttpServlet {@Overridepublic void doget (HttpServletRequest request, HttpServletResponse response) throws IOException {PrintWriter out = Response.getwriter ();//Because of browser reasons (FireFox, IE has this problem, Chrome is normal), the received data will not be exported to the page immediately. This first enters a string of length greater than 1024.

StringBuilder sb = new StringBuilder (); for (int i = 0; i < 1024x768; i++) {sb.append (' a ');} Out.println ("<!--" + sb.tostring () + "--"); Note Plus HTML gaze out.flush (); while (true) {//Here simulates comet with thread.sleep, equivalent to a message that is pushed by the server to the client every 5 seconds. {Thread.Sleep (5000) ;} catch (Interruptedexception e) {e.printstacktrace ();} Write a JS to the IFRAME every 5 seconds to call the parent's addmsg function. Add content to HTML Out.println ("<script>parent.addmsg (' helloworld<br> ') </script>"); Out.flush (); This must be flush, otherwise the data will not be sent}}}

I found in the test process Firefox, ie these browsers received the server response is not immediately loaded, the browser is equivalent to a cache. When it reaches a certain size, it will be loaded.

I tested Firefox to be 1024 bytes, so I wrote a string greater than 1024 bytes to the response before the servlet pushed the message to prevent the browser from loading in time. Chrome doesn't have this problem.

IFRAME-based flow There is a small problem is that because the IFRAME has not been loaded, in the connection state, the progress of all browsers will always show that is not complete, is always in the circles.


2.2, the way for Firefox

In Firefox, AJAX-enabled readystate gets request.responsetext for 3 o'clock, which means that the request is not complete to get partial response data. Such a way is not supported by other browsers such as IE.

Front page:

<! DOCTYPE html>

T= "+math.random (); var request = new XMLHttpRequest (); request.onreadystatechange = function () {if (request.readystate = = 3) {if (Request.responsetext) {//note here is no longer an append html,responsetext including all previous messages Document.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 (); and while (true) {// Here we use Thread.Sleep to simulate comet. The equivalent of every 5 seconds that the server pushes a message to the client try {thread.sleep),} catch (Interruptedexception e) {e.printstacktrace ();} Out.println ("helloworld<br>"); Out.flush (); Be sure to flush here. Otherwise the data is not sent}}}


Finally, the background Java code in this article is just for learning and demonstrating comet. It is not practical to use. The backstage is simply a simple sleep without any function to say, because Comet uses an HTTP long connection. When the client shuts down and the server is still blocked, the servlet does not stop. This is very critical. While Tomcat and jetty have a proven approach to comet technology, I'll continue to introduce it in my blog post.



Fork Brother reproduced please indicate the source: http://blog.csdn.net/xiao__gui/article/details/38331225



Introduction to Comet and the simplest Java Demo

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.