Very simple ......
Write another Servlet and start the corresponding thread in the init function.
Add this servlet to Web. XML, for example
<Servlet>
<Servlet-Name> echoservicestartupservlet </servlet-Name>
<Servlet-class> echoservice. echoservicestartupservlet </servlet-class>
<Load-on-startup> 3 </load-on-startup>
</Servlet>
Pay attention to load-on-startup.
The value after the number must be greater than 0, indicating the priority. The smaller the value, the higher the priority.
If this parameter is not set or smaller than 0, the instance is not started.
But there is a big problem !! That is, when Tomcat is disabled, the thread may not be released.
Listener should be used.
Code
Public Class Serversocketlistener Implements Servletcontextlistener {
Private Echoserverthread;
Public Void Contextinitialized (servletcontextevent event ){
String Port = Event. getservletcontext (). getinitparameter ( " Socketport " );
// Event. getservletcontext (). log ("++ ");
// Event. getservletcontext (). Log ("++ socket service started with the Web ");
Echoserverthread = New Echoserverthread (integer. parseint (port ));
Echoserverthread. Start ();
// Event. getservletcontext (). Log ("++ socket service has been started, Port:" + port + "++ ");
}
// When Tomcat is closed, the thread is closed and the port is released.
Public Void Contextdestroyed (servletcontextevent event ){
Echoserverthread. stopthread ();
}
}
The START and release operations are now available ~~~
Configure the following in Web. xml:
Add the following content to the Web-app node:
<Context-param>
<Param-Name> socketport </param-Name>
<Param-value> 2230 </param-value>
</Context-param>
<Listener>
<Description> the socket service is started with the Web startup. </description>
<Listener-class> echoservice. serversocketlistener </listener-class>
</Listener>