java – ServerSocket in web app


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


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;

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        server = new ServerSocket(PORT);
        // ...   

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

If you are using Servlet API older than 3.0 – add listener to web.xml


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

public class SocketServerListener implements ServletContextListener {

Scroll to Top