Java uses comet4j to proactively push information to clients simple examples

Source: Internet
Author: User
Tags thread class

Background

Today, a front-end of the younger brother asked me how to do real-time Chat window, I do not hesitate to say: At the front desk to access the server! The younger brother quietly Baidu, finally told me, there is a technology is after the service to push the message to the client, the name of this technology is comet, I was stunned, because completely did not hear, hurriedly surf the internet to collect information, consumed a night to write a simple example, to achieve the initiative to send information to the client. Said to say that the initiative, in fact, or to the client first give its "first", that is, as long as it has asked you first, after you cooked, you want to take the initiative about it!

For the introduction of comet technology and its implementation principles, you can refer to the website http://www.ibm.com/developerworks/cn/web/wa-lo-comet/introduction.

Simply put, the client sends the request to the server side, which blocks the request until there is a data pass or timeout before returning, and the client-side JavaScript response handler then makes the request again after processing the information returned by the server and re-establishes the connection. When the client processes the received data, re-establishes the connection, the server side may have new data arrival; The information is saved by the server until the client re-establishes the connection, and the client will retrieve all the information from the current server at once.

"Working Environment"

1, myeclipse2013

2. Tomcat 6.0

3. JDK 7

4. Firefox browser

Description :

The successful browsers are: (1) Mozilla Firefox (2) IE10, IE9, IE8 (3) 360 Fast browser Speed mode

The browsers that failed the test are: (1) IE10 compatibility mode, IE7

  

"Ready to Work"

1. Download Comet4j.js:http://files.cnblogs.com/xiaomzjm/comet4j.js.rar

2. Download Comet4j-tomcat6.jar:http://files.cnblogs.com/xiaomzjm/comet4j-tomcat6.jar.rar

3, to the Tomcat directory under the--conf--server.xml, the

    <connector port= "8080" protocol= "http/1.1"               connectiontimeout= "20000"               redirectport= "8443"/>

modified to:

<connector uriencoding= "UTF-8"     connectiontimeout= "20000"     port= "8080"       protocol= " Org.apache.coyote.http11.Http11NioProtocol "     redirectport=" 8443 "/>

Description 

In fact, the JS file and Jar official website is https://code.google.com/p/comet4j/, but it is Google, here is the celestial, so put two of my folder inside the address of the package.

Comet4j-tomcat6.jar there is another version of Comet4j-tomcat7.jar, choose the appropriate version to download. Tomcat under 6 must not be the right one.

Comet4j.js official documentation for use: http://doc.comet4j.tk/jsdocs/

Comet4j-tomcat6.jar official documentation for use: http://doc.comet4j.tk/apidocs/

  

"New Project Procedure"

(1) New server-side class Testcomet to implement Servletcontextlistener interface

(2) The interceptor should be configured in Web. XML :

    <listener>        <listener-class>org.comet4j.core.CometAppListener</listener-class>    </ listener>    <listener>        <description>HelloWorld</description>        <listener-class >com.zjm.www.test.TestComet</listener-class>    </listener>    <servlet>        < Display-name>cometservlet</display-name>        <servlet-name>CometServlet</servlet-name>        <servlet-class>org.comet4j.core.CometServlet</servlet-class>    </servlet>    < servlet-mapping>        <servlet-name>CometServlet</servlet-name>        <url-pattern>/conn </url-pattern>    </servlet-mapping>

Note : There are two places to configure

One is a servlet under the Comet4j-tomcat6.jar:org.comet4j.core.CometServlet, the portal for client access

The other is the listener under Comet4j-tomcat6.jar:Org.comet4j.core.CometAppListener , listening to our own class.

"The specific code (instructions are written in the comments)"

1. Web. xml

<?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 ">
<listener>
<listener-class>org.comet4j.core.CometAppListener</listener-class>
</listener>
<listener>
<description>HelloWorld</description>
<listener-class>com.zjm.www.test.TestComet</listener-class>
</listener>
<servlet>
<display-name>CometServlet</display-name>
<servlet-name>CometServlet</servlet-name>
<servlet-class>org.comet4j.core.CometServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CometServlet</servlet-name>
<url-pattern>/conn</url-pattern>
</servlet-mapping>


<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app version= "2.5" 3 xmlns= "http://java.sun.com/xml/ns/javae E "4 xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "5 xsi:schemalocation=" Http://java.sun.com/xml/ns/java EE 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> 7 <listener> 8 <listener-class>or G.comet4j.core.cometapplistener</listener-class> 9 </listener>10 <listener>11 &LT;DESCRI Ption>helloworld</description>12 <listener-class>com.zjm.www.test.testcomet</listener-class         >13 </listener>14 <servlet>15 <display-name>cometservlet</display-name>16 <servlet-name>cometservlet</servlet-name>17 <servlet-class>org.comet4j.core.cometservlet</ servlet-class>18 </servlet>19 <servlet-mapping>20 <servlet-name>cometservlet</serv Let-name>21 <url-pattern>/conn</url-pattern>22 </servlet-mapping>23 <welcome-file-list>26 <we lcome-file>index.jsp</welcome-file>27 </welcome-file-list>28 </web-app>

2. Java class Testcomet

There are a lot of comments attached, if you want to carefully study the recommendations of the above-mentioned API documentation links.

Package com.zjm.www.test;

Import javax.servlet.ServletContextEvent;
Import Javax.servlet.ServletContextListener;

Import Org.comet4j.core.CometContext;
Import Org.comet4j.core.CometEngine;

/**
* Description: Server-side proactive push message to client simple example
* @author ZJM
* @time 2014/8/7
*/
public class Testcomet implements Serv Letcontextlistener {

//Channel 1
private static final String CHANNEL1 = "RESULT1";
//Channel 2
private static F inal String CHANNEL2 = "RESULT2";

//The variable that is pushed to the foreground by Channel 1
private static int number1 = 0;
//The variable that is pushed to the foreground via Channel 2 2
private static int number2 = 10 0;

/**
* Initialization Context
*/
public void contextinitialized (Servletcontextevent arg0) {

//Cometcontext : comet4j context, which is responsible for initializing the configuration, engine objects, connector objects, message caches, and so on.
Cometcontext cc = Cometcontext.getinstance ();
//Register channels, that is, identify which fields are available as channels for the "channel"
Cc.registchannel (CHANNEL1) that transmits data to the foreground;
Cc.registchannel (CHANNEL2);

Thread myThread = new Thread (new Sendtoclientthread (), "Sendtoclientthread"); The method of the
///Following inner class is a dead loop, and setting the Helloappmodule thread to "daemon thread" will end when the JVM has only "daemon" (the main thread ends).
Mythread.setdaemon (TRUE);
//Start thread
Mythread.start ();
}

/**
* Internal class Thread class
*/
Class Sendtoclientthread implements Runnable {
public void Run () {
while (true) {
try {
Thread.Sleep (1000);
} catch (Exception ex) {
Ex.printstacktrace ();
}
Cometengine: Engine, responsible for managing and maintaining connections, and being able to send services as necessary
Cometengine engine = Cometcontext.getinstance (). Getengine ();
Parameter: What data (number1++) is sent through what channel (CHANNEL1), the foreground can use the value of the available channel (RESULT1) to get the data sent by a channel
Engine.sendtoall (CHANNEL1, number1++);
Engine.sendtoall (CHANNEL2, number2++);
}
}
}

public void contextdestroyed (Servletcontextevent arg0) {
}
}


 1 package com.zjm.www.test; 2 3 Import javax.servlet.ServletContextEvent; 4 Import Javax.servlet.ServletContextListener; 5 6 Import Org.comet4j.core.CometContext; 7 Import Org.comet4j.core.CometEngine; 8 9/**10 * Description: Server-side proactive push message to client simple example * @author zjm12 * @time 2014/8/713 */14 public class Testcomet implements Servle         Tcontextlistener {15 16//Channel 117 private static final String CHANNEL1 = "RESULT1"; 18//Channel 219 private static final String CHANNEL2 = "RESULT2"; 20 21//variable 122 private static that is pushed to the foreground via Channel 1          int number1 = 0; 23//variable via Channel 2 pushed to foreground 224 private static int number2 = 100; 25 26/**27                 * Initialization Context */29 public void contextinitialized (Servletcontextevent arg0) {30 31 The cometcontext:comet4j context, which is responsible for initializing the configuration, engine objects, connector objects, message caches, and so on. + Cometcontext cc = Cometcontext.getinstance (), 33//Register channel, which identifies which fields are available as channels and serves as a "channel" for transmitting data to the foreground 3 4                 Cc.registchannel (CHANNEL1); Cc.registchannel (CHANNEL2); 36 37 Thread myThread = new Thread (new Sendtoclientthread (), "Sendtoclientthread"), 38//The following method of the inner class is a dead loop, set The helloappmodule thread is the daemon thread, and the thread ends when the JVM is left with a daemon thread (the main thread ends). Mythread.setdaemon (TRUE); 40//Start thread Mythread.start (); 42}43 4                 4/**45 * Internal class thread Class */47 class Sendtoclientthread implements Runnable {48                                         public void Run () {$ while (true) {51                                         Thread.Sleep (Exception ex) {53 Ex.printstacktrace ();}55//Comete Ngine: Engine, responsible for managing and maintaining connections, and being able to send services as necessary cometengine engine = CometContext.getinstance (). Getengine (); 57//Parameter meaning: what channel (CHANNEL1) to send what data (number1++), the value of available channels available in the foreground                                 (RESULT1) To obtain data sent by a channel Engine.sendtoall (CHANNEL1, number1++); 59 Engine.sendtoall (CHANNEL2, number2++);}61}62}63 IC void contextdestroyed (Servletcontextevent arg0) {65}66}

3. Client code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>comet4j Hello world</title>
<script type= "Text/javascript" src= "Js/comet4j.js" ></script>
<script type= "Text/javascript" >
function init () {

var number1 = document.getElementById (' number1 ');
var number2 = document.getElementById (' number2 ');
Establish a connection, conn that is the <url-pattern> of Cometservlet in Web. xml
Js. Engine.start (' conn ');
Listen to a channel in the background
Js. Engine.on (
{
The value of "Channel 1" corresponding to the service end RESULT1
Result1:function (NUM1) {
number1.innerhtml = NUM1;
},
The value of "Channel 2" corresponding to the service end RESULT2
Result2:function (num2) {
number2.innerhtml = num2;
},
}
);
}
</script>
<body onload= "init ()" >
Digital 1:<span id= "Number1" >...</span><br></br>
Digital 2:<span id= "Number2" >...</span>
</body>

 1 <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 2 

4. Web page display

As you can see, two numbers are continuously incremented per second. The number 2 is 100 more than the number 1, because on the server side, the initial value of Number2 is 100,number1 with an initial value of 0.

Press F12 on the browser, select Network, as you can see, this connection has never been disconnected.

There is something wrong or not written in the place, welcome everyone to ask ~

Category: Java_web

Java uses comet4j to proactively push information to clients simple examples

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.