Matt Slater
Matt Slater

Reputation: 65

How to subscribe to a spring websocket message broker from an external client?

I've successfully implemented a simple websockets application with Spring Boot using this tutorial as a guide. The app can successfully connect to the STOMP endpoint, subscribe to the topic and get a response back.

To keep everything up with this microservices trend, I've been trying make the client external to the spring boot app. I can successfully connect to the STOMP endpoint using http://localhost:8080/delivery-ws I can't, however, subscribe and get updates from the spring boot app usinghttp://localhost:8080/topic/openDeliveries as would be expected.

Is there any way to subscribe to topic/openDeliveries externally?

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/delivery-ws").setAllowedOrigins("*").withSockJS();
    }
}

DeliveryController.java

@Controller
@RequestMapping("deliveries")
public class DeliveryController {

    private DeliveryRepository repository;
    SimpMessagingTemplate template;

    @Autowired
    public DeliveryController(DeliveryRepository repository, SimpMessagingTemplate template) {
        this.repository = repository;
        this.template = template;
    }

    public void updateListandBroadcast() {
        System.out.println("in update and broadcast");
        template.convertAndSend("/topic/openDeliveries", getOpenDeliveries());
    }


    public List<Delivery> getOpenDeliveries() {
        return repository.findByDeliveredFalse();
    }


    @RequestMapping(value = "/new", method = RequestMethod.POST)
    public @ResponseBody Delivery newDelivery(@RequestBody Delivery delivery) {
        Delivery d = repository.save(delivery);
        updateListandBroadcast();
        return d;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public @ResponseBody void delete(@PathVariable String id) {
        repository.delete(Long.parseLong(id));
        updateListandBroadcast();
    }

}

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Active Deliveries</title>
  <script src="sockjs-0.3.4.js"></script>
  <script src="stomp.js"></script>
  <script src="jquery-3.0.0.js"></script>
  <script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
      document.getElementById('connect').disabled = connected;
      document.getElementById('disconnect').disabled = !connected;
      document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
      document.getElementById('response').innerHTML = '';
    }

    function connect() {
      var socket = new SockJS('http://localhost:8080/delivery-ws');
      stompClient = Stomp.over(socket);
      stompClient.connect({}, function(frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('http://localhost:8080/openDeliveries', function(deliveryList) {
          console.log('in callback for opendelivery topic');
          showDeliveries(deliveryList);
        });
      });
    }

    function disconnect() {
      if (stompClient != null) {
        stompClient.disconnect();
      }
      setConnected(false);
      console.log("Disconnected");
    }

    function showDeliveries(list) {
      console.log('in show deliveries');
      var response = document.getElementById('response');
      response.innerHTML = list.body;


    }
  </script>
</head>

<body onload="disconnect()">
  <h1>Deliveries</h1>
  <noscript>
    <h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
    Javascript and reload this page!</h2>
  </noscript>
  <div>

    <div>
      <button id="connect" onclick="connect();">Connect</button>
      <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
    </div>
    <div id="conversationDiv">
      <p id="response"></p>
      <table id="data-table"></table>
    </div>
  </div>

</body>

</html>

Upvotes: 0

Views: 3226

Answers (1)

Aditya
Aditya

Reputation: 78

You need to change the url you are trying to subscribe to. Something like this:

stompClient.subscribe('/topic/openDeliveries', function(deliveryList) {
      console.log('in callback for opendelivery topic');
      showDeliveries(deliveryList);
});

Once connection to socket endpoint is made no need to have host and port defined in subscription.

Upvotes: 2

Related Questions