Search code examples
androidspring-bootwebsocketspring-websocketokhttp

Sending message to Spring Boot websocket endpoint method from Android


I have created a basic websockets example app using spring boot from their documentation.

this is my socket conf in spring boot :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends 
AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic");
    registry.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry 
stompEndpointRegistry) {

stompEndpointRegistry.addEndpoint("/message").setAllowedOrigins("*");
}
}

and this is my message controller

@Controller
public class MessageController {

private static final Logger logger = 
LoggerFactory.getLogger(MessageController.class);

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting sendResponse(Message incomingMessage) {
    logger.debug(incomingMessage.getMessage());
    return new Greeting("Hello " + incomingMessage.getMessage());
}
}

and i use okhttp from android to connect to the socket using the following code :

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding mBinding;
private static String TAG;
public static final String SOCKET_ADDR = 
"wss://androidspy.herokuapp.com/message";
private OkHttpClient mOkHttpClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, 
R.layout.activity_main);

TAG = this.getClass().getSimpleName();
initObjects();
initListeners();
initiateHandshake();
}

private void initObjects() {
mOkHttpClient = new OkHttpClient();
}

private void initListeners() {
//mBinding.btnConnect.setOnClickListener(this::initiateHandshake);
}

private void initiateHandshake() {
Request socketRequest = new Request.Builder()
    .url(SOCKET_ADDR)
    .build();

WebSocket webSocket = mOkHttpClient.newWebSocket(socketRequest, new 
WebSocketListener() {
  @Override
  public void onOpen(WebSocket webSocket, Response response) {
    webSocket.send("Hi Server");
    Log.d(TAG, String.format("Connected to 
%s",webSocket.request().url()));
  }

  @Override
  public void onMessage(WebSocket webSocket, String result) {
    Log.d(TAG, String.format("Received %s" ,result));
  }
 });
mOkHttpClient.dispatcher().executorService().shutdown();
}

with the above code,the connection get succeeded without any issues.but i dont get any response in onMessage Callback.

I want to know how do i send a message from the android client so that it calls the sendResponse() method in the spring server mapped with @MessageMapping("/hello).


Solution

  • Try to not close the connection mOkHttpClient.dispatcher().executorService().shutdown();