Skip to content

[Pattern] WebSocket clients with java.net.http #183

Description

@brunoborges

Category

io

Slug

http-websocket-client

Title

WebSocket clients with java.net.http

Difficulty

intermediate

Since JDK

11

Summary

Use the standard asynchronous WebSocket client instead of custom protocol handling or third-party clients.

Old code label

Third-party WebSocket client

Old code

WebSocketClient client = new WebSocketClient(serverUri) {
    @Override
    public void onMessage(String message) {
        handle(message);
    }
};
client.connect();

Modern code label

Java 11+

Modern code

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);
            }
        });

Explanation

The java.net.http package includes an asynchronous WebSocket client integrated with the standard HTTP client and CompletionStage-based flow.

Why the modern way wins

📦 No extra dependency — The client ships with the JDK.
🧵 Asynchronous API — Connection and message handling compose with CompletionStage.
🔗 Shared HTTP stack — Proxy, TLS, and client configuration use standard JDK facilities.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    slugNew or updated pattern snippet (category/slug.json)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions