Jochen
Jochen

Reputation: 1853

Embedded Jetty - use WebSocketUpgradeFilter together with AsyncProxyServlet

I've got a class that extends AsyncProxyServlet to do proxying with Jetty:

Server httpProxy = new Server();
ServletHolder servletHolder = new ServletHolder(TunnelProxyServlet.class);
HandlerCollection handlers = new HandlerCollection();
httpProxy.setHandler(handlers);

ServletContextHandler contextHandler = new ServletContextHandler(handlers, "/", ServletContextHandler.SESSIONS);
        
contextHandler.addServlet(servletHolder, "/*");

Now I'd like to add WebSocket support to this.

I tried this:

try {
    WebSocketUpgradeFilter.configure(contextHandler);
    NativeWebSocketServletContainerInitializer.configure(contextHandler, ((context, container) ->
    {
      container.addMapping("/*", (req, resp) -> new WebSocketProxy().getWebSocketConnectionListener());
    }));
   } catch (ServletException ex) {
     Logger.getLogger(HttpProxy.class.getName()).log(Level.SEVERE, ex.getMessage());
   }

But the code never reaches this point.

How can I do proxying with WebSockets?

Upvotes: 0

Views: 491

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49515

WebSocket Proxy is a very large and complicated topic.

First, let me start by saying that WebSocket proxying is possible starting with Jetty 10.

The basic support for WebSocket proxy was added to Jetty 10 in https://github.com/eclipse/jetty.project/pull/3365

Sadly, Jetty 9 has no support for WebSocket Proxy. Either built into Jetty itself, or with enough core features within Jetty's WebSocket layer to allow you to implement it yourself.

Next, Jetty's AsyncProxyServlet is not capable of handling upgraded connections (like WebSocket). That class can only handle HTTP requests (be it HTTP/1.0, HTTP/1.1, or HTTP/2. With HTTP/3 support in the near future).

Some advice, when you do WebSocket proxying, you'll need to decide how you do it.

Are you going to proxy the frames as-is? (easiest, and most recommended approach).

Are you going to want to read the frame content? (requires complicated extension manipulation, extension preservation, frame preservation, and the ability to read partial messages from the frame level, etc)

Are you going to want to read the whole message (1..n frames) content? (this quadruples your memory requirements for websocket as its : remote websocket client -> websocket proxy server -> your proxy interested in messages -> websocket proxy client -> websocket backend server)

Upvotes: 1

Related Questions