Search code examples
javaconfigurationwebsocketjettyjetty-9

Can i run WebAppContext with WebSocketHandler in same instance?


is it possible to run WebSocketHandler and WebAppContext together? I'm using latest version 9.2.1.v20140609. I tried configuration below, but on Websocket call to localhost:8080/ WebAppContext intercepts call. Here is my Launcher:

public static void main(String[] args) throws Exception
{
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8080);
    server.addConnector(connector);

    WebAppContext context = new WebAppContext("webapp", "/");

    // Setting up browser caching. Binds params for org.eclipse.jetty.servlet.DefaultServlet.init()
    context.getInitParams().put("org.eclipse.jetty.servlet.Default.etags", "true");
    context.getInitParams().put("org.eclipse.jetty.servlet.Default.cacheControl", "public, max-age=0");

    // Fix for Windows, so Jetty doesn't lock files
    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        context.getInitParams().put("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    // Will throw an exception when will be unable to start server for some reason
    context.setThrowUnavailableOnStartupException(true);

    Broker broker = new Broker();

    // Implementation of org.eclipse.jetty.websocket.server.WebSocketHandler
    WebSocketHandler socketHandler = new com.namespace.websocket.Handler(broker);

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] {context, socketHandler});

    server.setHandler(handlerCollection);

    // Remove Server:Jetty(9...) from Response Headers
    removeServerVersionFromHeaders(server);

    server.start();

}

I can run from launcher multiple jetty instances and just wire WebSocket handler to some 5555 port, but preferably i would like to keep one Jetty instance, and maybe use /ws handler to manage WebSocket connections


Solution

  • How about something like:

    public class Websock {
      private static class Adapter extends WebSocketAdapter {
        @Override
        public void onWebSocketConnect(Session sess) {
          System.out.print("client connected");
        }
      }
    
      public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
    
        WebAppContext context = new WebAppContext("webapp", "/");
        context.getServletHandler().setEnsureDefaultServlet(false); // may or may not be needed.
    
        ContextHandlerCollection handlerCollection = new ContextHandlerCollection();
        handlerCollection.addHandler(context);
        handlerCollection.addHandler(createWebsocketHandler());
    
        server.setHandler(handlerCollection);
    
        server.start();
      }
    
      private static ContextHandler createWebsocketHandler() {
        ContextHandler contextHandler = new ContextHandler("/ws");
        contextHandler.setAllowNullPathInfo(true); // disable redirect from /ws to /ws/
    
        final WebSocketCreator webSocketcreator = new WebSocketCreator() {
          public Object createWebSocket(ServletUpgradeRequest request,
              ServletUpgradeResponse response) {
            return new Adapter();
          }
        };
    
        Handler webSocketHandler = new WebSocketHandler() {
          public void configure(WebSocketServletFactory factory) {
            factory.setCreator(webSocketcreator);
          }
        };
    
        contextHandler.setHandler(webSocketHandler);
        return contextHandler;
      }
    }
    

    ContextHandlerCollection seems like what you want, takes a bit of getting used to chaining the jetty handlers together.

    If you don't need the features of WebAppContext then you can remove that too and just use ContextHandlers directly.

    I haven't ran this myself but it looks about right.