Search code examples
javawebsocketlistenermessagehtmlunit

Reaching onmessage websocket event HtmlUnit


I want to read the messages received by a websocket in onmessage event. I follow the explanation made in this thread

I only achieved to add a Listener and be informed when the websocket is created but I don´t know how to read the messages received by the websocket in onmessage event.

Here is my code:

    public class TestBet365Socket {
  public static void main(String[] args) throws Exception {


      /* turn off annoying htmlunit warnings */
        java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);



        WebClient client = new WebClient(BrowserVersion.CHROME);  
        client.getOptions().setCssEnabled(false);  
        client.getOptions().setJavaScriptEnabled(true);
        client.getOptions().setThrowExceptionOnScriptError(false);



        client.getInternals().addListener(new Listener() {

            @Override
            public void webSocketCreated(WebSocket arg0) {

                System.out.println("Websocket Created " + arg0);

            }
        });



        HtmlPage page = client.getPage("https://mobile.bet365.com/Default.aspx?lng=3");
        client.waitForBackgroundJavaScript(10000);

        List<NameValuePair> response =page.getWebResponse().getResponseHeaders();
        for (NameValuePair header : response) {
             System.out.println(header.getName() + " = " + header.getValue());
         }
        System.out.println(page.asText());

        client.close();
  }
}

Solution

  • You have to do two things:

    1. implement you own listener

    Create a class that implements org.eclipse.jetty.websocket.api.WebSocketListener. Inside this class you can implement you way of capturing the socket communication.

    1. set the listener

    The method webSocketCreated() gots a WebSocket instance as parameter. Call setWebSocketListener(yourListener) with the listener you have created in the first step.

    Now you are done and your listener will be called every time the websocket gots data.