A simple example of using comet4j to actively push information to the client in java

Source: Internet
Author: User

A simple example of using comet4j to actively push information to the client in java
Today, a front-end teacher asked me how to make a real-time chat window. I did not hesitate to say: access the server regularly at the front-end! The younger brother quietly tried Baidu and finally told me that there was a technology that was subsequently pushed to the client by the server. The name of this technology was comet. I was shocked because I had never heard of it, it took one night to write a simple example to actively send information to the client. To say "active", the client needs to give it the "First time", that is, as long as it has requested you first, you will be familiar with it later. If you want to take the initiative to ask for it, you will ask it! About the introduction of comet Technology and Its Implementation principle, can refer to the introduction of the website http://www.ibm.com/developerworks/cn/web/wa-lo-comet. Simply put, the client sends a request to the server, and the server blocks the request until data transmission or timeout is returned. After that, the client's JavaScript response processing function will process the information returned by the server, send a request again to establish a new connection. When the client processes received data and re-establishes a connection, new data may arrive at the server. The information will be saved by the server until the client re-establishes the connection, the client will retrieve all the information on the current server at a time. [Work Environment] 1. myeclipse2013 2. tomcat 6.0 3. jdk 7 4. Firefox browser Description: browsers that have been tested successfully include: (1) Firefox browser (2) IE10, IE9, and IE8 (3) 360 browsers that fail to test the speed mode of the speed browser include: (1) IE10 compatibility mode and IE7 [preparations] 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 -- conf -- server. in xml, set <Connector port = "8080" protocol = "HTTP/1.1" connectionTimeout = "20000" redirect Port = "8443"/> changed to: <Connector URIEncoding = "UTF-8" connectionTimeout = "20000" port = "8080" protocol = "org. apache. coyote. http11.Http11NioProtocol "redirectPort =" 8443 "/> note: in fact, the js file and jar official website is https://code.google.com/p/comet4j/, but it is Google, here is the day na, so I pasted two packages in my folder. Another version of The comet4j-tomcat6.jar is the comet4j-tomcat7.jar, and you can choose the appropriate version to download. Tomcat below 6 will certainly not work. Comet4j. js official documentation: http://doc.comet4j.tk/jsdocs/ comet4j-tomcat6.jar official documentation: http://doc.comet4j.tk/apidocs/ [new project process] (1) New server class TestComet, ServletContextListener interface (2) in the web. the interceptor should be configured in xml: copy the Code <listener> <listener-class> org. comet4j. core. cometAppListener </listener-class> </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> copy the code. Note: one of the two parts to be configured is a servlet under the comet4j-tomcat6.jar: org. comet4j. core. cometServlet, the client access portal is another comet4j-tomcat 6. The Listener in jar is org. comet4j. core. CometAppListener, which listens to our own class. [Specific code (instructions are written in comments)] 1. Copy code 1 from web. xml <? Xml version = "1.0" encoding = "UTF-8"?> 2 <web-app version = "2.5" 3 xmlns = "http://java.sun.com/xml/ns/javaee" 4 xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" 5 xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <listener> 8 <listener-class> org. comet4j. core. cometAppListener </listener-class> 9 </listener> 10 <listener> 11 <description> HelloWorld </description> 12 <listener-clas S> 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 </servlet-name> 21 <url-pattern>/conn </url-pattern> 22 </servlet-mapping> 23 24 25 <welcome-file-list> 26 <welcome-file> Index. jsp </welcome-file> 27 </welcome-file-list> 28 </web-app> copy code 2. Many comments are attached to java TestComet, if you want to study it carefully, you can see the link to the API documentation given above. Copy code 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: simple example 11 * @ author zjm12 * @ time 2014/8/713 */14 public class TestComet implements ServletContextListener {15 16 // channel 117 private static final String CHANNEL1 = "resu Lt1 "; 18 // channel 219 private static final String CHANNEL2 =" result2 "; 20 21 // The variable 122 private static int number1 = 0 pushed to the foreground through channel 1; 23 // The variable 224 private static int number2 = 100 pushed to the foreground through Channel 2; 25 26/** 27 * initialization context 28 */29 public void contextInitialized (ServletContextEvent arg0) {30 31 // CometContext: Comet4J context, responsible for Initialization Configuration, engine object, connector object, message cache, etc. 32 CometContext cc = CometContext. getInstance (); 33 // register the channel, that is, to identify which fields can be used as channels, used as the "channel" 34 cc for transmitting data to the foreground. registChannel (CHANNEL1); 35 cc. registChannel (CHANNEL2); 36 37 Thread myThread = new Thread (new SendToClientThread (), "SendToClientThread"); 38 // The internal class method below is an endless loop, if the helloAppModule thread is set to "daemon thread", the thread also ends when the jvm only has "daemon thread" (the main thread ends. 39 myThread. setDaemon (true); 40 // start thread 41 myThread. start (); 42} 43 44/** 45 * internal class Thread class 46 */47 class SendToClientThread implements Runnable {48 public void run () {49 while (true) {50 try {51 Thread. sleep (1000); 52} catch (Exception ex) {53 ex. printStackTrace (); 54} 55 // CometEngine: engine, responsible for managing and maintaining connections, and being able to send services necessary 56 CometEngine engine = CometContext. getInstance (). getEngine (); 57 // The meaning of the parameter: What channel (CHANNEL1) is used to send the data (Number1 ++), the foreground can use the value of available channels (result1) to obtain the data sent by a channel 58 engine. sendToAll (CHANNEL1, number1 ++); 59 engine. sendToAll (CHANNEL2, number2 ++); 60} 61} 62} 63 64 public void contextDestroyed (ServletContextEvent arg0) {65} 66} copy code 3. Copy code 1 from the client <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2

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.