我需要编写聊天功能,但遇到了一个问题,无法触发 MessageMapping controller
。该应用包括前端和后端两部分,前端运行在4200端口,后端运行在8080端口。我已经进行了所有配置,但是@MessageMapping controller
没有被触发。后端控制台没有任何输出,但浏览器控制台显示消息已发送。请帮我解决这个问题,以下是我的相关配置。
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
}
以下是控制器
@Controller
public class MessageController {
@MessageMapping("/chat")
@SendTo("/topic/message")
public void sendMessage(Message message) {
System.out.println("test");
}
还有前端部分是用Angular编写的:
(function (angular, SockJS, Stomp, _, undefined) {
"use strict";
angular.module("app").
factory("chatService", chatService);
chatService.$inject = ["$q", "$timeout"];
function chatService ($q, $timeout) {
var service = {}, listener = $q.defer(), socket = {
client: null,
stomp: null
}, messageIds = [];
service.RECONNECT_TIMEOUT = 30000;
service.SOCKET_URL = "http://localhost:8080/chat";
service.CHAT_TOPIC = "http://localhost:8080/topic/message";
service.CHAT_BROKER = "http://localhost:8080/app/chat";
service.receive = function() {
return listener.promise;
};
service.send = function(message) {
var id = Math.floor(Math.random() * 1000000);
socket.stomp.send(service.CHAT_BROKER, {
priority: 9
}, JSON.stringify({
message: message,
id: id
}));
messageIds.push(id);
};
var reconnect = function() {
$timeout(function() {
initialize();
}, this.RECONNECT_TIMEOUT);
};
var getMessage = function(data) {
var message = JSON.parse(data), out = {};
out.message = message.message;
out.time = new Date(message.time);
if (_.contains(messageIds, message.id)) {
out.self = true;
messageIds = _.remove(messageIds, message.id);
}
return out;
};
var startListener = function() {
socket.stomp.subscribe(service.CHAT_TOPIC, function(data) {
listener.notify(getMessage(data.body));
});
};
var initialize = function() {
socket.client = new SockJS(service.SOCKET_URL);
socket.stomp = Stomp.over(socket.client);
socket.stomp.connect({}, startListener);
socket.stomp.onclose = reconnect;
};
initialize();
return service;
}
})(angular, SockJS, Stomp, _);
浏览器控制台显示如下内容:
Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
version:1.1
heart-beat:0,0
user-name:test@test.com
connected to server undefined
vendor-cd0f7ffee3.js:113305
>>> SUBSCRIBE
id:sub-0
destination:http://localhost:8080/topic/message
>>> SEND
priority:9
destination:http://localhost:8080/app/chat
content-length:30
{"message":"test","id":490235}