Overview

This plugin is the same as the Spincast HTTP Client plugin but adds support for WebSockets.

We decided to create two separate versions because this one uses classes from Undertow, so more transitive dependencies are pulled into an application using it. We wanted to give the possibility to use the HTTP Client without those extra dependencies, if preferred. But note that if you are already using the default Server in your Spincast application, it is also based on Undertow, so you already pull those dependencies anyway...

All the WebSockets tests of Spincast use this HTTP client so have a look at them for a lot of examples!

Usage

WebsocketClientHandler websocketHandler = new WebsocketClientHandler() {

    @Override
    public void onEndpointMessage(String message) {
        System.out.println("Message received from the server: " + message);
    }

    @Override
    public void onEndpointMessage(byte[] message) {
        System.out.println("Binary message received from the server...");
    }

    @Override
    public void onConnectionClosed(int code, String reason) {
        System.out.println("WebSocket connection closed.");
    }
};

HttpClient httpClient = getHttpClient();

WebsocketClientWriter websocketWriter =
        httpClient.websocket("http://example.com/someEndpoint")
                  .setCookie("cookieKey", "cookieValue")
                  .setHeader("headerKey", "headerValue")
                  .connect(websocketHandler);

websocketWriter.sendMessage("Hi server!");

Explanation :

  • 1-17 : You define a WebSocket handler which is responsible for handling the WebSocket events.
  • 22-25 : You use the HTTP Client to connect to a WebSocket endpoint. Note that you can use all the utilities available from the HTTP core: addCookie(...), addHeader(...), etc.
  • 21 : A WebSocket writer is returned when to connection is established.
  • 27 : You use the writer to send message to the endpoint.

Configurations

You can bind the SpincastHttpClientWithWebsocketConfig interface if you want to change some default configurations. The default implementation class for those configurations is SpincastHttpClientWithWebsocketConfigDefault.

Suggested add-on

  • Name : httpClient()
  • Component : HttpClient
  • Usage : to be able to make HTTP and WebSockets requests easily from your Route Handlers.

Learn how to install an add-on in the dedicated section of the documentation.

Installation

1. Add this Maven artifact to your project:

<dependency>
    <groupId>org.spincast</groupId>
    <artifactId>spincast-plugins-http-client-with-websocket</artifactId>
    <version>2.2.0</version>
</dependency>

2. Add an instance of the SpincastHttpClientWithWebsocketPlugin plugin to your Spincast Bootstrapper:


Spincast.configure()
        .plugin(new SpincastHttpClientWithWebsocketPlugin())
        // ...

Plugin class

The class implementing the SpincastPlugin interface is SpincastHttpClientWithWebsocketPlugin.

Javadoc