Jetty9 How to properly close the WebSocketClient@ thread problem?

37 Views Asked by At

Jetty Version Jetty 9.4.53

Jetty Environment linux jetty run command: ./bin/jetty.sh run

Java Version 1.8.0_371 x64

Question I used this code to create a Websocket client connection

WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, URI.create(url));

If the server connection fails, this code will continue to be used during the reconnection. But each execution of this code creates eight threads of WebSocketClient@xxx-xxx The connection pool cannot be automatically destroyed if the connection fails. My code ContainerProvider.getWebSocketContainer(); -> org.eclipse.jetty.websocket.jsr356.ClientContainer<111 line> - > public ClientContainer() -> WebSocketClient <95 line>-> public WebSocketClient() -> DefaultHttpClientProvider.get -> DefaultHttpClientProvider.newHttpClient

Reconnecting will create a new thread pool and 8 threads. How do I close this object? Can't you create a Websocket client this way in Jetty?

thread image

How to properly close the WebSocketClient@ thread problem?

1

There are 1 best solutions below

0
Joakim Erdfelt On

The Jakarta WebSocket Client Container (aka jakarta.websocket.WebSocketContainer, or the older now deprecated and end-of-life javax.websocket.WebSocketContainer) is meant to be started only once, and you use that container over and over again until the JVM exits.

You don't create the container for each request.

You treat the container as you would a web browser you open only 1 web browser and use it to access many different sites.

This design decision by Jakarta EE WebSocket is intentional, as such there is no close/stop/shutdown API for the WebSocketContainer.

If you want to reconnect, just use one of the connectToServer() methods again.

There was an issue opened back in 2013 against the Jakarta EE WebSocket Spec to define such an API, but there's been no traction or interest in developing such an API.
https://github.com/jakartaee/websocket/issues/212