When the Javaweb service starts, it loads a thread in the background to perform a socket listening port

Source: Internet
Author: User

Recently, to do a project, you need to do a Web server, the server to communicate with the Android and GPRS modules. Consider the use of HTTP communication between Android and server, GPRS module and server with TCP communication. It is therefore necessary to start the load on the Web server when a thread is responsible for monitoring the TCP port.

Search a few ways to choose from two of them to record here:

Method One: monitoring (Listener)

We create a listener class that inherits from Servletcontextlistener, with the following code:

1  Packagewould ;2 3 4 Importjava.io.IOException;5 6 Importjavax.servlet.ServletContextEvent;7 ImportJavax.servlet.ServletContextListener;8 9  Public classSocketListenerImplementsServletcontextlistener {Ten  One     PrivateMyThread MyThread; A @Override -      Public voidcontextdestroyed (servletcontextevent arg0) { -         if(mythread!=NULL&&mythread.isinterrupted ()) { the mythread.interrupt (); -         } -  -     } +  - @Override +      Public voidcontextinitialized (servletcontextevent arg0) { AString str =NULL; at         if(str==NULL&&mythread==NULL) { -Mythread=NewMyThread (); -Mythread.start ();//start socket When servlet context is initialized -         } -     } -      in      -     /* to * Custom class thread classes inherit from the thread class, overriding the run () method for retrieving processing data from the background +      *  -      */ the     classMyThreadextendsthread{ *          Public voidrun () { $              while(! This. isinterrupted ()) {//thread does not interrupt execution loopPanax Notoginseng                 Try { -Thread.Sleep (2000);//executes every 2000ms the                      +                      A}Catch(interruptedexception e) { the e.printstacktrace (); +                 } -                  $                 //----------------------start Execution--------------------- $System.out.println ("Time:" +System.currenttimemillis ()); -              -Server ss=NewServer (); the                 Try { - ss.startwork ();Wuyi}Catch(IOException e) { the                     //TODO auto-generated Catch block - e.printstacktrace (); Wu                 } -             } About         } $     } -  -}

You need to add the following configuration in Web. xml:

1 < Listener > 2   < Listener-class >would. SocketListener</listener-class>3</Listener  >

Method Two: use the servlet to start the project when it starts.

We create a servlet that inherits HttpServlet, with the following code:

1Package would;2 Importjava.io.IOException; 3 Importjavax.servlet.ServletException; 4 ImportJavax.servlet.http.HttpServlet; 5 Importjavax.servlet.http.HttpServletRequest; 6 ImportJavax.servlet.http.HttpServletResponse; 7 Importcom.ite.common.Constants; 8   9  Public classMyservletextendshttpservlet{Ten    One     Private Static Final LongSerialversionuid = 1L;  A     PrivateMyThread1 MyThread1;  -        -      PublicMyservlet () { the     }   -    -      Public voidinit () { -String str =NULL;  +         if(str = =NULL&& MyThread1 = =NULL) {   -MyThread1 =NewMyThread1 ();  +Mythread1.start ();//start socket When servlet context is initialized A         }   at     }   -    -      Public voiddoget (httpservletrequest httpservletrequest, HttpServletResponse httpservletresponse) -         throwsservletexception, ioexception{ -     }   -    in      Public voiddestory () { -         if(MyThread1! =NULL&&mythread1.isinterrupted ()) {   to Mythread1.interrupt ();  +         }   -     }   the }   *    $ /** Panax Notoginseng * Custom class thread classes inherit from the thread class, overriding the run () method for retrieving and processing data from the background -  *   the  * @author would +  *   A  */   the classMyThread1extendsThread { +      Public voidrun () { -          while(! This. isinterrupted ()) {//thread does not interrupt execution loop $             Try {   $Thread.Sleep (2000);  -}Catch(interruptedexception e) { - E.printstacktrace ();  the             }   -               Wuyi             //------------------start Execution--------------------------- theSystem.out.println ("Time:" +System.currenttimemillis ());  -         }   Wu     }   -}

The corresponding configuration in Web. XML is:

1 <servlet>  2     <Servlet-name>MyListener</Servlet-name>  3     <Servlet-class>Would. Myservlet</Servlet-class>  4     <Load-on-startup>9</Load-on-startup><!--The smaller the number, the higher the priority of the boot, which must be greater than 0 -  5 </servlet>  6 <servlet-mapping>    7         <Servlet-name>MyListener</Servlet-name>    8         <Url-pattern>/test</Url-pattern>     9 </servlet-mapping>  

Socket port of the listening method is not written here, people directly in the "-----------start executing----------" after the call can be added

Where, in the listener way, the thread is definitely first started in the project and takes precedence over any servlet. And the servlet's way, you can set the order with other servlets to start. This can be useful if you sometimes need to start a servlet first, or if there are special requirements for the boot order between them.

When the Javaweb service starts, it loads a thread in the background to perform a socket listening port

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.