java – ServerSocket in web app

Question:

How can I embed ServerSocket into a web application on a specific port? When, how and where should you launch it?

Answer:

You can create a very basic socket server:

ServerSocket ss = new ServerSocket(port);

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

Actions to be performed 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 are using Servlet API older than 3.0 – add listener to web.xml

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

Starting with Servlet API 3.0, you just need to mark your class with the @WebListener annotation:

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

Scroll to Top