I/O Intermediate

Use the standard asynchronous WebSocket client instead of adding a third-party dependency.

✕ Third-party library
WebSocketClient client =
    new WebSocketClient(serverUri) {
        @Override
        public void onMessage(String message) {
            handle(message);
        }
    };
client.connect();
✓ Java 11+
HttpClient.newHttpClient()
    .newWebSocketBuilder()
    .buildAsync(serverUri,
        new WebSocket.Listener() {
            @Override
            public CompletionStage<?> onText(
                    WebSocket socket,
                    CharSequence data,
                    boolean last) {
                handle(data.toString());
                return WebSocket.Listener.super
                    .onText(socket, data, last);
            }
        });
See a problem with this code? Let us know.
📦

No extra dependency

The WebSocket client ships with the JDK.

🧵

Asynchronous API

Connection and message handling compose with CompletionStage.

🔗

Shared HTTP stack

Proxy, TLS, and executor configuration use standard JDK facilities.

Old Approach
Third-party WebSocket client
Modern Approach
java.net.http.WebSocket
Since JDK
11
Difficulty
Intermediate
WebSocket clients with java.net.http
Available

Widely available since JDK 11 (September 2018)

The java.net.http package includes an asynchronous WebSocket client integrated with the standard HTTP client. Connections are established with CompletableFuture, listener callbacks support non-blocking message processing through CompletionStage, and the client shares the JDK's standard proxy, TLS, and executor configuration.