问题
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.
- Don't mix
ResourceHandlerandServletContextHandler, use the built-in static file serving fromServletContextHandler, its Resource Base, and theDefaultServlet(see prior answer with details) - Don't put anything after your
ServletContextHandler(if yourServletContextHandleris on contextPath/). Once aServletContextHandleris entered (per the contextPath), then it must complete/finish (this is part of the servlet spec), no other handler after thatServletContextHandlerwill ever run. (see prior answer about this) - Don't mix
WebSocketHandlerandServletContextHandler, use theWebSocketUpgradeFilterin yourServletContextHandlerand add/manage the websocket endpoints there. (see the embedded-jetty-cookbook and the WebSocketViaFilter example for how to use it)
来源:https://stackoverflow.com/questions/34007087/jetty-9-add-websockets-handler-to-handler-list