如果使用STOMP Client在服务器端编码出现问题,我想向客户端发送警报。我在谷歌搜索过但没有找到任何例子,但我找到了STOMP client documentation。
我在控制器中编写了以下代码
WebSocketClient transport = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(transport);
stompClient.setMessageConverter(new StringMessageConverter());
String url = "ws://localhost:8080/SpringMVCStompClient/alert";
StompSessionHandler handler = new MySessionHandler();
stompClient.connect(url, handler);
和MyHandler代码是:
public class MySessionHandler extends StompSessionHandlerAdapter {
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
Alert alert= new Alert();
alert.setName("Server");
alert.setMessage("Message from server");
session.send("/topic/alert", alert);
}
}
当我尝试执行此执行时,不会转到MyHandler类。这是正确的方法吗?
帮帮我,我怎样才能向客户发送警报。
Websocket XML配置
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/alert">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
控制器
@Autowired
public SpringMVCController(SimpMessagingTemplate template) {
this.template = template;
}
@Autowired
private SimpMessagingTemplate template;
@MessageMapping("/alert")
@SendTo("/topic/alert")
public Alerts alerts(Alerts alerts) throws Exception {
Alert alert= new Alert();
alert.setName("Server");
alert.setMessage("Message from server");
this.template.convertAndSend("/topic/alert", alert);
return alerts;
}
客户端js代码服务
(function(angular, SockJS, Stomp) {
angular.module("alertApp.services").service("AlertService", function($q, $timeout) {
var service = {}, listener = $q.defer(), socket = {
client: null,
stomp: null
};
service.SOCKET_URL = "/SpringMVCStompClient/alert";
service.ALERT_TOPIC = "/topic/alert";
service.ALERT_BROKER = "/app/alert";
service.receive = function() {
return listener.promise;
};
service.send = function(alert) {
socket.stomp.send(service.ALERT_BROKER, { priority: 9}, JSON.stringify({
message: alert.message,
name: alert.name
}));
};
service.disconnect = function() {
socket.stomp.disconnect();
};
var startListener = function() {
socket.stomp.subscribe(service.ALERT_TOPIC, function(data) {
listener.notify(JSON.parse(data.body));
});
};
service.initialize = function() {
socket.client = new SockJS(service.SOCKET_URL);
socket.stomp = Stomp.over(socket.client);
socket.stomp.connect({}, startListener);
};
return service;
});
})(angular, SockJS, Stomp);