使用Angular2和Spring Boot通过Stomp协议实现SockJS

3
我希望在我的项目中实现一个websocket,用于处理通知。
这是我在Spring Boot项目中的websocket配置。
 @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

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

在我的控制器中,我有这个方法:

@MessageMapping("/hello")
    @SendTo("/topic/templatesWS")
    public void TemplatesWebSocket() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("calling juste");
    }

在我的客户端页面index.html中,我添加了以下内容:
<script src="//cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js"></script>

在我的Angular 2组件中,我正在使用以下代码:

declare let SockJS;
        declare let Stomp;


        var socket = new SockJS('http://localhost:8080/hello');
        socket.ono
        var stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('http://localhost:8080/template/topic/templatesWS', function(greeting) {
                console.log("from from", greeting);
            });
        }, function (err) {
            console.log('err', err);
        });

我该如何调用TemplatesWebSocket()方法?

enter image description here


我认为subscribe()参数应该简单地是'/topic/templatesWS'。 - Marcelus Trojahn
如何将数据发送到服务器或在事件触发后获取对象? - khalil _diouri
我解决了这个错误,我有一些配置websocket安全性,防止连接,但是代码行stompClient.subscribe没有调用控制器中的方法TemplatesWebSocket(),我该如何调用它? - khalil _diouri
1个回答

1

请查看我刚刚上传的示例: https://github.com/mtrojahn/spring-boot-websocket

我想你是想要向服务器发送命令并获得响应,对吗?上面的示例涵盖了客户端发送的命令的响应以及定期发送给客户端的消息。

您可能正在寻找类似以下内容的东西:

stompClient.client.send("/app/somecommand", {}, "");

我希望它有所帮助。


1
发送方法运行良好,但stompClient.subscribe不起作用。 我们为什么要使用subscribe方法?? 当我们在一个带有计划的方法中订阅时,例如每20秒获取一次数据,但在MessageMapping的情况下,如果您能解释给我,谢谢(我更新了问题,我添加了subscribe方法错误的图片) - khalil _diouri
Websockets 是关于订阅服务并等待数据的。服务器向所有已订阅的客户端推送(广播)数据。20s 的示例展示了这种情况,每 20 秒您的客户端将接收到一条消息。您遇到的 subscribe 方法未定义的问题似乎是浏览器加载脚本的顺序问题。 - Marcelus Trojahn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接