在web环境下,tomcat整合socket,使用 init() 初始化socket服务。无法启动tomcat
Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.
public void init() throws ServletException { // TODO 初始化serverSocket System.out.println("ScoketServlet"); try { //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口 ServerSocket serverSocket=new ServerSocket(60000); Socket socket=null; //记录客户端的数量 int count=0; System.out.println("***服务器即将启动,等待客户端的连接***"); //循环监听等待客户端的连接 while(true){ //调用accept()方法开始监听,等待客户端的连接 socket=serverSocket.accept(); //创建一个新的线程 ServerThread serverThread=new ServerThread(socket); //启动线程 serverThread.start(); count++;//统计客户端的数量 System.out.println("客户端的数量:"+count); InetAddress address=socket.getInetAddress(); System.out.println("当前客户端的IP:"+address.getHostAddress()); serverThread.stop(); } } catch (IOException e) { e.printStackTrace(); } }
检查发现在启动时候却因为使用 while 监听scoket,Init方法运行不能返回,从而ServletSocket不能运行结束,tomcat最后会因为启动失败而退出。
因而,现在为了解决这个问题,于是就将SocketServer封装在一个线程中