jetty 9 add websockets handler to handler list

2019-08-31 23:46发布

问题:

All handlers in that example work apart from the websockets handler

       WebSocketHandler wsHandler = new WebSocketHandler() {
        @Override
        public void configure(WebSocketServletFactory factory) {
            factory.register(WebsocketsService.class);
        }
    };

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resource_handler, servletContextHandler, wsHandler, new DefaultHandler() });
    server.setHandler(handlers);

it fails with

WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200

how would be a websockets handler properly configured and added (maybe with a differen Path and Port as the servletContextHandler or could it be added there ?) ?

回答1:

A few things.

  1. Don't mix ResourceHandler and ServletContextHandler, use the built-in static file serving from ServletContextHandler, its Resource Base, and the DefaultServlet (see prior answer with details)
  2. Don't put anything after your ServletContextHandler (if your ServletContextHandler is on contextPath /). Once a ServletContextHandler is entered (per the contextPath), then it must complete/finish (this is part of the servlet spec), no other handler after that ServletContextHandler will ever run. (see prior answer about this)
  3. Don't mix WebSocketHandler and ServletContextHandler, use the WebSocketUpgradeFilter in your ServletContextHandler and add/manage the websocket endpoints there. (see the embedded-jetty-cookbook and the WebSocketViaFilter example for how to use it)