简体   繁体   English

SockJS使用angular2和弹簧靴进行踩踏

[英]SockJS over stomp using angular2 and spring boot

I want to implement a websocket inside my projet to do something as notifications 我想在我的项目中实现一个websocket来做一些通知

this is my configuration web socket in my projet spring boot 这是我的projet弹簧启动中的配置Web套接字

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

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

and in my controller I have this method : 在我的控制器中我有这个方法:

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

and in my client side in my page index.html I added this 在我的客户端我的页面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>

and in my component angular2 I'm using this 在我的组件angular2我正在使用它

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);
        });

How can I call the method TemplatesWebSocket() 如何调用TemplatesWebSocket()方法

在此输入图像描述

Check this example I just uploaded: https://github.com/mtrojahn/spring-boot-websocket 检查我刚上传的这个例子: https//github.com/mtrojahn/spring-boot-websocket

I think what you meant is send a command to the server and get a response, right? 我想你的意思是向服务器发送命令并得到回复,对吧? The example above covers both the response to a command sent by the client and also periodic messages sent to the clients. 上面的示例包括对客户端发送的命令的响应以及发送到客户端的定期消息。

You are probably looking for something like this: 你可能正在寻找这样的东西:

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

I hope it helps. 我希望它有所帮助。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM