Package java.net.http

Interface WebSocket.Listener

Enclosing interface:
WebSocket

public static interface WebSocket.Listener
The receiving interface of WebSocket.

A WebSocket invokes methods of the associated listener passing itself as an argument. These methods are invoked in a thread-safe manner, such that the next invocation may start only after the previous one has finished.

When data has been received, the WebSocket invokes a receive method. Methods onText, onBinary, onPing and onPong must return a CompletionStage that completes once the message has been received by the listener. If a listener's method returns null rather than a CompletionStage, WebSocket will behave as if the listener returned a CompletionStage that is already completed normally.

An IOException raised in WebSocket will result in an invocation of onError with that exception (if the input is not closed). Unless otherwise stated if the listener's method throws an exception or a CompletionStage returned from a method completes exceptionally, the WebSocket will invoke onError with this exception.

API Note:
The strict sequential order of invocations from WebSocket to Listener means, in particular, that the Listener's methods are treated as non-reentrant. This means that Listener implementations do not need to be concerned with possible recursion or the order in which they invoke WebSocket.request in relation to their processing logic.

Careful attention may be required if a listener is associated with more than a single WebSocket. In this case invocations related to different instances of WebSocket may not be ordered and may even happen concurrently.

CompletionStages returned from the receive methods have nothing to do with the counter of invocations. Namely, a CompletionStage does not have to be completed in order to receive more invocations of the listener's methods. Here is an example of a listener that requests invocations, one at a time, until a complete message has been accumulated, then processes the result, and completes the CompletionStage:

    WebSocket.Listener listener = new WebSocket.Listener() {

    List<CharSequence> parts = new ArrayList<>();
    CompletableFuture<?> accumulatedMessage = new CompletableFuture<>();

    public CompletionStage<?> onText(WebSocket webSocket,
                                     CharSequence message,
                                     boolean last) {
        parts.add(message);
        webSocket.request(1);
        if (last) {
            processWholeText(parts);
            parts = new ArrayList<>();
            accumulatedMessage.complete(null);
            CompletionStage<?> cf = accumulatedMessage;
            accumulatedMessage = new CompletableFuture<>();
            return cf;
        }
        return accumulatedMessage;
    }
};
Since:
11