简体   繁体   English

如何从外部客户端订阅spring websocket消息代理?

[英]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. 我已使用本教程作为指南,使用Spring Boot成功实现了一个简单的websockets应用程序。 The app can successfully connect to the STOMP endpoint, subscribe to the topic and get a response back. 该应用程序可以成功连接到STOMP端点,订阅主题并获得响应。

To keep everything up with this microservices trend, I've been trying make the client external to the spring boot app. 为了跟上这种微服务趋势的发展,我一直在尝试使客户端在spring boot应用程序外部。 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 using http://localhost:8080/topic/openDeliveries as would be expected. 我可以使用http://localhost:8080/delivery-ws成功连接到STOMP端点,但是,我可以像使用http://localhost:8080/topic/openDeliveries一样从spring boot应用程序订阅并获取更新。被期望。

Is there any way to subscribe to topic/openDeliveries externally? 有什么办法可以topic/openDeliveries外部订阅topic/openDeliveries

WebSocketConfig.java 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 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 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> 

You need to change the url you are trying to subscribe to. 您需要更改您要订阅的URL。 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. 一旦建立了到套接字端点的连接,就不需要在订阅中定义主机和端口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 适用于WebSocket Message Broker的Android客户端 - Android Client for WebSocket Message Broker Spring作为Broker Relay使用外部Message Broker - Spring as Broker Relay by using an external Message Broker 在Spring 4中创建websocket消息代理的多个实例 - Creating multiple instances of websocket message broker in Spring 4 Java Websocket:如何从Websocket客户端接收PongMessage并响应此消息 - Java websocket: How to receive PongMessage from websocket client and respond to this message 如何调用websocket服务器在春天将消息发送到客户端 - How to call the websocket server to sends the message to the client in spring Spring Webflux WebSocket 客户端 - 如何处理不同的消息结构? - Spring Webflux WebSocket Client - how to handle different message structures? 如何订阅内部Spring Boot / Simple Broker主题队列? - How to subscribe an internal Spring Boot/Simple Broker topic queue? 在集群环境中使用外部消息代理(RabbitMQ)将Spring套接字转换并发送给用户 - spring socket convertandsendtouser with external message broker(RabbitMQ) in cluster environment Spring 4 WebSocket远程代理配置 - Spring 4 WebSocket Remote Broker configuration 如何在 android 上通过 spring 启动从 stomp websocket 接收消息? - How to receive the message from stomp websocket with spring boot on android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM