How can I build ServerSocket on a specific port in a web application? When, how and where should I run it?

    1 answer 1

    You can create the most common socket server:

    ServerSocket ss = new ServerSocket(port); 

    If you just need an entry point in the web application that starts when the application starts, write a class that implements the javax.servlet.ServletContextListener interface and contextInitialized() method to initialize your socket server.

    Actions that must be contextDestroyed() when the web application is stopped are performed in the contextDestroyed() method

     public class SocketServerListener implements ServletContextListener { private static final int PORT = 3333; private ServerSocket server; @Override public void contextInitialized(ServletContextEvent servletContextEvent) { server = new ServerSocket(PORT); // ... } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { server.close(); } } 

    If you use a Servlet API older than 3.0, add a listener to the web.xml

     <listener> <listener-class>my.package.SocketServerListener</listener-class> </listener> 

    Starting with Servlet API 3.0, all you need to do is annotate your class with @WebListener :

     @WebListener public class SocketServerListener implements ServletContextListener { //... } 

    • If you don't mind, I will slightly correct the question and answer so that they better reflect the essence of our discussion. - Nofate