NoobsPlanet

Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics, posts and unlimited download to our resources, as well as connect with other members through your own private inbox!

Java Spring Websocket Backend - Stomp Client In Android

QueenDevelopers

New member
In this tutorial I will use NaikSoftware Library to connect to server as backend (Spring Boot), You can take a demo look to library for server, I will just go step by step for Android.

WebSocketConfig.groovy:
@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue", "/exchange");
//        config.enableStompBrokerRelay("/topic", "/queue", "/exchange"); // Uncomment for external message broker (ActiveMQ, RabbitMQ)
        config.setApplicationDestinationPrefixes("/topic", "/queue"); // prefix in client queries
        config.setUserDestinationPrefix("/user");
    }

    @Override
    void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/example-endpoint").withSockJS()
    }
}
SocketController.groovy:
@Slf4j
@RestController
class SocketController {

    @MessageMapping('/hello-msg-mapping')
    @SendTo('/topic/greetings')
    EchoModel echoMessageMapping(String message) {
        log.debug("React to hello-msg-mapping")
        return new EchoModel(message.trim())
    }
}
Check out the full example server
https://github.com/NaikSoftware/stomp-protocol-example-server

For Android
Add com.github.NaikSoftware:StompProtocolAndroid:1.6.4 library to project and also add io.reactivex.rxjava2:rxjava:2.2.5 which is required to dispose connection, I will explain this later.

build.gradle:
implementation 'com.github.NaikSoftware:StompProtocolAndroid:1.6.4'
implementation 'io.reactivex.rxjava2:rxjava:2.2.5'
This requires java to be set to minimum 8 on compile time so set the compileOptions to Java-8.
build.gradle:
android {
        .........
              compileOptions {
                  sourceCompatibility 1.8
                  targetCompatibility 1.8
           }
    }
I will create a create called WebsocketClient.class and Add the following lines of code.
Android:
String WEBSOCKET_CONNECT_URL="ws://example.com/ws"
String WEBSOCKET_TOPIC="/user/queue/"

private void connectWebSocket(Activity activity) {
        compositeDisposable = new CompositeDisposable();
        mStompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, WEBSOCKET_CONNECT_URL);
        Disposable lifecycle = mStompClient.lifecycle().subscribe(lifecycleEvent -> {
            switch (lifecycleEvent.getType()) {
                case OPENED:
                    Log.i(Konstant.TAG, "Stomp Connection Opened");
                    break;
                case ERROR:
                    Log.d(Konstant.TAG, "Error ", lifecycleEvent.getException());
                    break;
                case CLOSED:
                    Log.w(Konstant.TAG, "Stomp Connection Closed");

                    break;
                case FAILED_SERVER_HEARTBEAT:
                    Log.d(Konstant.TAG, "Failed Server Heartbeat ");
                    break;
            }
        });
        if (!mStompClient.isConnected()) {
            mStompClient.connect();
        }

        Disposable topic = mStompClient.topic(WEBSOCKET_TOPIC).subscribe(stompMessage -> {
           Log.d(TAG,stompMessage.getPayload());
         // Do your code here when ever you receive data from server.
        }, throwable -> Log.d(TAG,throwable.getMessage().toString()+""));
        compositeDisposable.add(lifecycle);
        compositeDisposable.add(topic);
    }

  public static void connectSocket() {
        if (mStompClient != null) {
            if (!mStompClient.isConnected()) {
               connectWebSocket
            }
        }

    public static void disconnectSocket() {
        if (mStompClient != null) {
            if (mStompClient.isConnected()) {
                mStompClient.disconnect();
//                compositeDisposable.dispose();
            }
        }

    }
So, in the above code mStompClient is static variable, you can connect the websocket from any class like :
Connect Websocket:
WebsocketClient.connectSocket();
WebsocketClient.disconnectSocket();
 
Last edited:
Top