Я использовал Spring MVC (4.2.2.RELEASE) и Tomcat 8. Мое требование - отправить уведомление в браузер. Пожалуйста, найдите код ниже.Stomp subscribe callback не работает Spring MVC
Контроллер -------------- @Controller общественного класса MessageController { // @ Autowired частный шаблон SimpMessagingTemplate; @ Автоматический шаблон шаблона SimpMessageSendingOperations; Список noteList = новый ArrayList();
public MessageController() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
//@SubscribeMapping("/topic/notify")
//@SendToUser("/topic/notify")
public void sendMessage(String msg){
Notification note = new Notification();
note.setMsg(msg);
noteList.add(note);
template.convertAndSend("/topic/price", noteList);
}
}
Configuration
---------------
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/queue","/topic");
}
}
Client code
---------
var socket = new SockJS("/intl-fcstone/ws");
var stompClient = Stomp.over(socket);
var connectCallback = function() {
console.log('----inside connectCallback before----');
stompClient.subscribe('/topic/price', notifyUser);
console.log('----inside connectCallback after----');
};
var errorCallback = function(error) {
console.log('----inside errorCallback----');
alert(error.headers.message);
};
stompClient.connect("guest", "guest", connectCallback, errorCallback);
function notifyUser(frame) {
console.log('----inside notifyUser1----'+frame);
console.log('----inside notifyUser2----'+frame.body);
var notes = JSON.parse(frame.body);
console.log('----inside notifyUser3----'+notes);
if(notes !=''){
var $messageDiv = $('#notification_div'); // get the reference of the div
$messageDiv.show().html(notes);
}
Chrome console
---------------
Opening Web Socket...
stomp.js:134 Web Socket Opened...
stomp.js:134 >>> CONNECT
login:guest
passcode:guest
accept-version:1.1,1.0
heart-beat:10000,10000
stomp.js:134 <<< CONNECTED
version:1.1
heart-beat:0,0
user-name:[email protected]
stomp.js:134 connected to server undefined
(index):159 ----inside connectCallback before----CONNECTED
user-name:[email protected]
heart-beat:0,0
version:1.1
stomp.js:134 >>> SUBSCRIBE
id:sub-0
destination:/topic/price
(index):161 ----inside connectCallback after----CONNECTED
user-name:[email protected]
heart-beat:0,0
version:1.1
---------------------------
after this, nothing happens.
http://localhost:8080/intl-fcstone/ws/info shows
{
entropy: -646614392,
origins: [
"*:*"
],
cookie_needed: true,
websocket: true
}
Any help on this is much appreciated.
спасибо Charnjeet. Я думаю, что моя проблема другая. https://gerrydevstory.com/2014/03/04/spring-4-websocket-stock-ticker-example/ – Tiger
Большое спасибо, Charnjeet Singh за ваш ответ. Я думаю, что моя проблема другая. https://gerrydevstory.com/2014/03/04/spring-4-websocket-stock-ticker-example/ Приведенный выше пример отлично работает на моем сервере. В хромированной консоли, я могу ясно видеть после >>> ПОДПИСАТЬСЯ ID: суб-0 назначения:/тема/цена <<< MESSAGE назначения:/тема/цена типа содержимого: приложения/JSON; кодовыми = UTF-8 подписка: под-0 message-id: _pv5roji-93 content-length: 2 Но этого не хватает в моем текущем проекте. Я не уверен, почему подписка в этом случае не происходит. – Tiger