Tomcat工作时超时

时间:2015-04-07 08:05:47

标签: java tomcat servlets

首先 - 我对servlet和所有其他Java EE工作的经验都很少。

我正在尝试制作简单的聊天室,但在此之前我只是尝试制作简单的udp服务器和客户端。一切正常,除了45秒后tomcat超时并关闭的一件事。我只有一个contextListener,它调用UDP服务器类。

是因为我没有servlet,还是?..

这是我的UDP服务器类:

public UDPServer() {
    System.out.println("Constructor reached");
    try {
        connect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


 public void connect() throws Exception
 {
    int serverPort = 9123;
    System.out.println("Server is starting");
    DatagramSocket serverSocket = new DatagramSocket(serverPort);
    System.out.println("Server started");
       byte[] receiveData = new byte[1024];
       byte[] sendData = new byte[1024];
       while(true)
          {
             DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
             serverSocket.receive(receivePacket);
             String sentence = new String( receivePacket.getData());
             System.out.println("RECEIVED: " + sentence);
             InetAddress IPAddress = receivePacket.getAddress();
             int port = receivePacket.getPort();
             String capitalizedSentence = sentence.toUpperCase();
             sendData = capitalizedSentence.getBytes();
             DatagramPacket sendPacket =
             new DatagramPacket(sendData, sendData.length, IPAddress, port);
             serverSocket.send(sendPacket);
             receiveData =  new byte[1024];
             sendData = new byte[1024];
          }
 }

这是我的简单contextListener

public class StartupServlet implements ServletContextListener {

// private static Logger logger = Logger.getAnonymousLogger(ApplicationListener.class);

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
       // logger.info("class : context destroyed");

    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext context = servletContextEvent.getServletContext();
        ///// HERE You launch your class
        UDPServer udpserver = new UDPServer();
       // logger.info("myapp : context Initialized");
    }

}

这是web.xml

<web-app>
<listener>
    <listener-class>com.chatroom.servlet.StartupServlet</listener-class>
</listener>
</web-app>

1 个答案:

答案 0 :(得分:2)

UDP服务器在与servlet初始化程序线程相同的线程中运行,并且它具有无限循环。因此,应用程序无法启动。在单独的线程中运行UDPServer。