我想在我的projet中实现一个websocket来做一些事情作为通知
这是我的projet spring boot中的配置Web套件
@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>
在我的组件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);
});
如何调用TemplatesWebSocket()
方法答案 0 :(得分:1)
检查此示例我刚刚上传: https://github.com/mtrojahn/spring-boot-websocket
我认为您的意思是向服务器发送命令并获得响应,对吧?上面的示例包括对客户端发送的命令的响应以及发送给客户端的定期消息。
你可能正在寻找这样的东西:
stompClient.client.send("/app/somecommand", {}, "");
我希望它有所帮助。