GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • โ†
  • โ†’

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev โ€” WebSocket clients with java.net.http | java.evolved

Home / I/O / WebSocket clients with java.net.http
I/O Intermediate

WebSocket clients with java.net.http

  • ๐Ÿ› Report a code issue
  • ๐ŸŒ Report a translation issue
  • ๐Ÿ’ก Suggest a new pattern

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

HTTP I/O Async Programming
Code Comparison
โœ• 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);
            }
        });
Share ๐•
See a problem with this code? Let us know.
Why the modern way wins
๐Ÿ“ฆ

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
JDK Support
WebSocket clients with java.net.http
Available

Widely available since JDK 11 (September 2018)

How it works

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.

Related Documentation
WebSocket โ†— HTTP Client (JEP 321) โ†—
Proof
View proof source โ†—
Related patterns
I/O Beginner

Modern HTTP client

Java 8
URL url = new URL("https://api.com/data");
HttpURLConnection con =
    (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
// read lines, close streams...
Java 11+
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.com/data"))
    .build();
var response = client.send(
    request, BodyHandlers.ofString());
String body = response.body();
Hover to see modern โžœ
JDK 11+ โ†’
Concurrency Intermediate

CompletableFuture chaining

Pre-Java 8
Future<String> future =
    executor.submit(this::fetchData);
String data = future.get(); // blocks
String result = transform(data);
Java 8+
CompletableFuture.supplyAsync(
    this::fetchData
)
.thenApply(this::transform)
.thenAccept(IO::println);
Hover to see modern โžœ
JDK 8+ โ†’
Concurrency Intermediate

Concurrent HTTP with virtual threads

Java 8
ExecutorService pool =
    Executors.newFixedThreadPool(10);
List<Future<String>> futures =
    urls.stream()
    .map(u -> pool.submit(
        () -> fetchUrl(u)))
    .toList();
// manual shutdown, blocking get()
Java 21+
try (var exec = Executors
    .newVirtualThreadPerTaskExecutor()) {
    var results = urls.stream()
        .map(u -> exec.submit(
            () -> client.send(req(u),
                ofString()).body()))
        .toList().stream()
        .map(Future::join).toList();
}
Hover to see modern โžœ
JDK 21+ โ†’
You are visitor 01402503 โ€” GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร—600. No cookies required.