WebSocket clients with java.net.http
Use the standard asynchronous WebSocket client instead of adding a third-party dependency.
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);
}
});
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
Proof