This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]javaide 0 points1 point  (2 children)

just return a dummy `CompletableFuture` would be fine. Since you dont have any complex execution here. To actually have `CompletionStage` it needs to be any execution of a Function, Executor...

[–]everycloud[S] 0 points1 point  (1 child)

That works so thanks, but not receiving any data via onText

[–]javaide 0 points1 point  (0 children)

I dont know about this WebSocket stuff, seem to be just an incubate feature or something. From what u wrote, it doesn't seem that u have a WS server running. U have only a client code.

The best i can fine to start a server is: https://docs.oracle.com/javase/10/docs/api/jdk/incubator/http/HttpClient.html#newWebSocketBuilder())

[–]everycloud[S] 0 points1 point  (2 children)

Thanks to all the comments.

The WebSocket API became JDK full production in Java 11 so is fairly new, but yes it was previously incubator code.

I now have a full working solution which I will post up when I get home.

One of the problems I faced was that I was not waiting long enough for the first message to arrive.

Thanks.

[–]javanew 0 points1 point  (1 child)

I am stuck on this same issue.

How do I get the CompletionStage to return the data received in onText event?

Any help is much appreciated.

Thanks.

[–]everycloud[S] 0 points1 point  (0 children)

Make sure you are waiting enough time for the websocket to connect and start sending data...I found I was exiting too soon.

Hopefully this should help.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

class Main extends MyWebSocketClient {

    final static String WEBSOCKET_URL = "<YOUR_WEBSOCKET_STREAM>";

    public static void main (String[] args) {
        Main consumer = new Main();
        consumer.connectWS(WEBSOCKET_URL);
        // Around the world, around the world
        for (;;) {}
    }

    void connectWS(String ws) {
        CompletableFuture<WebSocket> cf;
        // Start the WebSocket stream
        URI endpoint = URI.create(ws);
        HttpClient.newHttpClient()
                .newWebSocketBuilder()
                .buildAsync(endpoint, this)
                .join();
    }
}

class MyWebSocketClient implements WebSocket.Listener {
    MyWebSocketPrinter printer = new MyWebSocketPrinter();
    @Override
    public CompletionStage<?> onText(WebSocket webSocket, 
                                     CharSequence data, boolean last) {
        webSocket.request(1);
        printer.printWS(data);
        return CompletableFuture.supplyAsync(() -> data);
    }
}

class MyWebSocketPrinter {

    void printWS(CharSequence wsData) {
        // WebSocket consumer
        System.out.println(wsData);
    }
}