All Downloads are FREE. Search and download functionalities are using the official Maven repository.

templates.plugins.spincast-http-client-with-websocket.spincast-http-client-with-websocket.html Maven / Gradle / Ivy

There is a newer version: 0.9.28
Show newest version
{#==========================================
Spincast HTTP Client with WebSockets support plugin
==========================================#}
{% extends "../../layout.html" %}

{% block sectionClasses %}plugins plugins-spincast-http-client-with-websocket{% endblock %}
{% block meta_title %}Plugins - Spincast HTTP Client with WebSockets support{% endblock %}
{% block meta_description %}Client to easily create and send HTTP requests and establish WebSocket connections.{% endblock %}

{% block scripts %}

{% endblock %}

{% block body %}

Overview

This plugin is the same as the regular Spincast HTTP Client 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!

Make sure you read the documentation of the regular HTTP Client since most of the functionalities are documented there. Here, we're only going to focus on the WebSockets specificities.

Installation

Add this artifact to your project:

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

Then, install the plugin's Guice module, by passing it to the Guice.createInjector(...) method:

Injector guice = Guice.createInjector(
        new AppModule(args),
        new SpincastHttpClientWithWebsocketPluginGuiceModule(IAppRequestContext.class, 
                                                             IAppWebsocketContext.class)
        // other modules...
        );

... or by using the install(...) method from your custom Guice module:

public class AppModule extends SpincastDefaultGuiceModule {

    //...

    @Override
    protected void configure() {
        super.configure();
        install(new SpincastHttpClientWithWebsocketPluginGuiceModule(getRequestContextType(), 
                                                                     getWebsocketContextType()));
        // other modules...
    }
    
    // ...
}

Usage

Again, make sur you read the documentation of the regular client too. Here, we're only going to focus on WebSockets specificities:

IWebsocketClientHandler websocketHandler = new IWebsocketClientHandler() {

    @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.");
    }
};

IHttpClient httpClient = getHttpClient();

IWebsocketClientWriter websocketWriter =
        httpClient.websocket("http://example.com/someEndpoint")
                  .addCookie("cookieKey", "cookieValue")
                  .addHeaderValue("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.

IHttpClient's methods

The object used to start the creation of a WebSocket connection request.

  • IWebsocketRequestBuilder websocket(String url)
    Starts the builder to create a WebSocket connection request.

IWebsocketRequestBuilder's methods

The builder object used to create a WebSocket connection request. You obtain an instance by calling IHttpClient#websocket(...)

  • IWebsocketRequestBuilder ping(int seconds)
    You can use this to configure the pings that are automatically sent to the Websocket endpoint every X seconds. IWebsocketClientHandler#onConnectionClosed() will be called if the connection is closed.

    Use a value <= 0 to disable the pings.

    The automatic pings and their default interval are also configurable using: ISpincastHttpClientWithWebsocketConfig#isWebsocketAutomaticPingEnabled()
    and
    ISpincastHttpClientWithWebsocketConfig#getWebsocketAutomaticPingIntervalSeconds()

    Pings are enabled by default.

    @param seconds the interval in seconds or <= 0 to disable the pings.
  • IWebsocketClientWriter connect(IWebsocketClientHandler handler)
    Sends the request and establish the WebSocket connection.
    @param handler The handler that is responsible to handle the various WebSocket events.
    @return a writer to send Websocket messages to the connected endpoint.
  • @Override public IHttpResponse send()
    Sends the request and gets the HTTP response. Does not make the actual upgrade to a WebSocket connection! Use the connect(...) method if you want the actual WebSocket connection to be made.

    This version is useful to debug the intermediate HTTP upgrade response made from the server before the actual WebSocket connection is established.

IWebsocketClientWriter's methods

The object you receive when your request is sent and the WebSocket connection is established successfully. You use it to send messages and to close the connection.

  • void sendMessage(String message)
    Sends a text message to the endpoint.
  • void sendMessage(byte[] message)
    Sends a binary message to the endpoint
  • void closeConnection()
    Closes the WebSocket connection.

Configurations

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

Here are the available configurations:

  • boolean isWebsocketAutomaticPingEnabled()
    Are automatic pings enabled when a WebSocket connection is established?
    Default to true.
  • int getWebsocketAutomaticPingIntervalSeconds()
    When automatic pings are enabled for WebSocket connections, how many seconds should be waited between two pings?
    Defaults to 20 seconds.
  • String getWebsocketPingMessageString()
    The ping text to use. Must be < 125 characters.
    Defaults to "__ping"
  • int getWebsocketThreadExecutorForClientEventsThreadNumber()
    The maximum number of concurrent threads used when sending events to the IWebsocketClientHandler.
    Defaults to 10.
  • int getWebsocketThreadExecutorForClientEventsTimeoutAmount()
    The timeout amount before cancelling a task when sending events to the IWebsocketClientHandler.
    Defaults to 60.
  • TimeUnit getWebsocketThreadExecutorForClientEventsTimeoutTimeUnit()
    The timeout TimeUnit before cancelling a task when sending events to the IWebsocketClientHandler.
    Defaults to SECONDS.
  • ThreadFactory getWebsocketThreadExecutorForClientEventsThreadFactory()
    The ThreadFactory to use to create threads to send WebSocket events to the IWebsocketClientHandler.
    Defaults to null.
  • int getWebsocketDefaultClosingCode()
    The default code to send to the IWebsocketClientHandler when a WebSocket connection was found to be closed.
    Valid codes can be found here
    Defaults to 1001: "1001 indicates that an endpoint is "going away", such as a server going down or a browser having navigated away from a page.."
  • String getWebsocketDefaultClosingReason()
    The default reason to send to the IWebsocketClientHandler when a WebSocket connection was found to be closed.
    Defaults to an empty message.

{% endblock %}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy