Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require assistance with simple pure Java 11 WebSocket client example

There appears to be very little Java 11 (pure Java non framework based) WebSocket client code examples on the web so I'm hoping StackOverflow can come to the rescue for me once again.

This is the closest I've found, but unfortunately to my (novice) eyes, it doesn't appear to be a complete solution in showing how to consume the data from the WebSocket listener.

Looking at the WebSocket.Listener implementation, the onText callback method I presume would provide what I need, but I'm struggling to figure out how to return the CompletionStage object and some sort of string data from the socket.

This is some test code I have so far.

Would appreciate assistance. Thanks

    public class Main {

        public static void main(String[] args) {

           WebSocketClient wsc = new WebSocketClient();
           wsc.startSocket("ws://demos.kaazing.com/echo");

           int i = 0;   

           // Bad, very bad
           do {} while (i == 0);
        }
    }


    public class WebSocketClient implements WebSocket.Listener {

        @Override
        public void onOpen(WebSocket webSocket) {
           //...
            System.out.println("Go...Open".concat(
                    webSocket.getSubprotocol()));
        }

        @Override
        public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
           //...
            System.out.println(data.toString());

            // How do I return the CompletionStage object
            // return CompletionStage<String>
        }

        @Override
        public void onError(WebSocket webSocket, Throwable error) {
           //..
            System.out.println("Bad day! ".concat(webSocket.toString()));
        }

        void startSocket(String connection) {
            CompletableFuture<WebSocket> server_cf = HttpClient.
                    newHttpClient().
                    newWebSocketBuilder().
                    buildAsync(URI.create(connection),
                            new WebSocketClient());
            WebSocket server = server_cf.join();
            server.sendText("Hello!", true);
        }
    }
like image 504
eodeluga Avatar asked Mar 27 '19 15:03

eodeluga


People also ask

What is a WebSocket example?

Here's an example: let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello"); socket. onopen = function(e) { alert("[open] Connection established"); alert("Sending to server"); socket. send("My name is John"); }; socket.

What is WebSocket client Java?

public WebSocketClient(URI serverUri) Constructs a WebSocketClient instance and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. The connection will be established once you call connect . Parameters: serverUri - the server URI to connect to.


1 Answers

Below you find a working example. I have made some changes to your code above:

  • onOpen needs to invoke request(1) on the websocket (invoking the default implementation) in order to receive further invocations.
  • moved method startSocket into the main method
  • replaced busy waiting with a count down latch
  • declared class WebSocketClient as a (static) inner class

but beyond these (cosmetic) changes the program follows your idea, i.e. first a websocket connection is build and after successful construction the text Hello! is sent to the echo server. This could also be done in method onOpen directly.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
        
public class Main {
        
    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        
        WebSocket ws = HttpClient
                .newHttpClient()
                .newWebSocketBuilder()
                .buildAsync(URI.create("ws://demos.kaazing.com/echo"), new WebSocketClient(latch))
                .join();
        ws.sendText("Hello!", true);
        latch.await();
    }
            
    private static class WebSocketClient implements WebSocket.Listener {
        private final CountDownLatch latch;
                
        public WebSocketClient(CountDownLatch latch) { this.latch = latch; }
        
        @Override
        public void onOpen(WebSocket webSocket) {
            System.out.println("onOpen using subprotocol " + webSocket.getSubprotocol());
            WebSocket.Listener.super.onOpen(webSocket);
        }
        
        @Override
        public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
            System.out.println("onText received " + data);
            latch.countDown();
            return WebSocket.Listener.super.onText(webSocket, data, last);
        }
        
        @Override
        public void onError(WebSocket webSocket, Throwable error) {
            System.out.println("Bad day! " + webSocket.toString());
            WebSocket.Listener.super.onError(webSocket, error);
        }
    }
}

Btw, no supprotocol was negotiated, therefore method webSocket.getSubprotocol() returns an empty string. The output in the console is

    onOpen using subprotocol 
    onText received Hello!
like image 107
Dominik Avatar answered Oct 17 '22 12:10

Dominik