Java › Java Networking & HTTP Client

How would you implement a WebSocket client using java.net.http.WebSocket for real-time, bidirectional communication, and how does its event-driven Listener interface work?

Advanced

Answer

HttpClient.newWebSocketBuilder().buildAsync(uri, listener) establishes a WebSocket connection, with a custom WebSocket.Listener implementation receiving callback invocations for connection lifecycle events (onOpen), incoming text/binary messages (onText/onBinary), and connection closure (onClose) or errors (onError) -- sending messages uses the resulting WebSocket instance's sendText()/sendBinary() methods (themselves returning a CompletableFuture indicating when the send completes), making this a fully asynchronous, callback-driven API well suited to real-time bidirectional communication scenarios like a chat client or live data feed subscriber.
WebSocket.Listener listener = new WebSocket.Listener() {
    public void onOpen(WebSocket webSocket) {
        System.out.println("Connected");
        WebSocket.Listener.super.onOpen(webSocket);
    }
    public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
        System.out.println("Received: " + data);
        return WebSocket.Listener.super.onText(webSocket, data, last);
    }
};

WebSocket webSocket = client.newWebSocketBuilder()
    .buildAsync(URI.create("wss://echo.example.com"), listener)
    .join();
webSocket.sendText("Hello!", true);
Real-world example A real-time price-monitoring client connects to a financial data provider's WebSocket feed using java.net.http.WebSocket, receiving continuous price update messages via the onText() callback and reacting to each one immediately, without needing a separate third-party WebSocket library dependency.

Common follow-ups: Why must Listener implementations typically call the super method (WebSocket.Listener.super.onText()) at the end of their own overrides -- what does the default implementation do?;How would you implement automatic reconnection logic if the WebSocket connection drops unexpectedly?