Spring Websocket + SockJS + Stomp - Контроллер не получает сообщения, несмотря на успешное соединение - PullRequest
0 голосов
/ 27 сентября 2019

У меня проблемы с тем, чтобы мой контроллер получал сообщения от моего веб-сокета при развертывании на внешнем Tomcat.При тестировании со встроенным Tomcat приложение работало отлично.При развертывании на внешнем Tomcat я изменил свой URL с "/ chat" на "/ mywebapp / chat" соответственно в своем файле javascript.При загрузке страницы сокет подключается успешно (если я не сделаю это изменение, подключение к сокету не будет установлено, поэтому этот URL-адрес правильный)Я получаю сердцебиение и все такое, но когда я отправляю сообщение, мой контроллер не получает его, а это означает, что сопоставление моего контроллера неверно.

Мой javascript:

        function connect() {
            var socket = new SockJS('/spring-boot-web-jsp-1.0/chat');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/spring-boot-web-jsp-1.0/topic/messages', function(messageOutput) {
                    showMessageOutput(JSON.parse(messageOutput.body));
                });
            });
            stompClient.debug = function(str) {
            // append the debug log to a #debug div somewhere in the page using JQuery:
                $("#debug").append(str + "\n");
            };
        }

        function sendMessage() {
            var from = document.getElementById('from').value;
            var text = document.getElementById('text').value;
            stompClient.send("/spring-boot-web-jsp-1.0/app/chat", {},
              JSON.stringify({'from':from, 'text':text}));
        }

Мои соответствующие журналы отладки:

Успешное соединение с клиентом:

2019-09-27 00:37:01.535 DEBUG 4699 --- [http-nio-8080-exec-1276] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2019-09-27 00:37:01.544 DEBUG 4699 --- [http-nio-8080-exec-1276] s.w.s.h.LoggingWebSocketHandlerDecorator : New WebSocketServerSockJsSession[id=ubdpn0zo]
2019-09-27 00:37:01.549 TRACE 4699 --- [http-nio-8080-exec-1276] o.s.w.s.adapter.NativeWebSocketSession   : Sending TextMessage payload=[o], byteCount=1, last=true], StandardWebSocketSession[id=1f, uri=ws://15.164.52.74:8080/spring-boot-web-jsp-1.0/chat/630/ubdpn0zo/websocket]
2019-09-27 00:37:01.558 TRACE 4699 --- [http-nio-8080-exec-1276] s.w.s.s.t.s.WebSocketServerSockJsSession : Scheduled heartbeat in session ubdpn0zo
2019-09-27 00:37:01.591 TRACE 4699 --- [http-nio-8080-exec-1281] s.w.s.h.LoggingWebSocketHandlerDecorator : Handling TextMessage payload=[CONNECT
ac..], byteCount=60, last=true] in WebSocketServerSockJsSession[id=ubdpn0zo]
2019-09-27 00:37:01.601 TRACE 4699 --- [http-nio-8080-exec-1281] o.s.w.s.m.StompSubProtocolHandler        : From client: CONNECT session=ubdpn0zo
2019-09-27 00:37:01.627 TRACE 4699 --- [clientOutboundChannel-1] s.w.s.s.t.s.WebSocketServerSockJsSession : Cancelling heartbeat in session ubdpn0zo
2019-09-27 00:37:01.628 TRACE 4699 --- [clientOutboundChannel-1] s.w.s.s.t.s.WebSocketServerSockJsSession : Preparing to write SockJsFrame content='a["CONNECTED\nversion:1.2\nheart-beat:0,0\n\n\u0000"]'
2019-09-27 00:37:01.628 TRACE 4699 --- [clientOutboundChannel-1] s.w.s.s.t.s.WebSocketServerSockJsSession : Writing SockJsFrame content='a["CONNECTED\nversion:1.2\nheart-beat:0,0\n\n\u0000"]'
2019-09-27 00:37:01.628 TRACE 4699 --- [clientOutboundChannel-1] o.s.w.s.adapter.NativeWebSocketSession   : Sending TextMessage payload=[a["CONNECT..], byteCount=53, last=true], StandardWebSocketSession[id=1f, uri=ws://15.164.52.74:8080/spring-boot-web-jsp-1.0/chat/630/ubdpn0zo/websocket]
2019-09-27 00:37:01.629 TRACE 4699 --- [clientOutboundChannel-1] s.w.s.s.t.s.WebSocketServerSockJsSession : Scheduled heartbeat in session ubdpn0zo
2019-09-27 00:37:01.647 TRACE 4699 --- [http-nio-8080-exec-1286] s.w.s.h.LoggingWebSocketHandlerDecorator : Handling TextMessage payload=[SUBSCRIBE
..], byteCount=73, last=true] in WebSocketServerSockJsSession[id=ubdpn0zo]
2019-09-27 00:37:01.647 TRACE 4699 --- [http-nio-8080-exec-1286] o.s.w.s.m.StompSubProtocolHandler        : From client: SUBSCRIBE /spring-boot-web-jsp-1.0/topic/messages id=sub-0 session=ubdpn0zo
2019-09-27 00:37:03.440 TRACE 4699 --- [http-nio-8080-exec-1282] s.w.s.h.LoggingWebSocketHandlerDecorator : Handling TextMessage payload=[SEND
desti..], byteCount=115, last=true] in WebSocketServerSockJsSession[id=ubdpn0zo]
2019-09-27 00:37:03.440 TRACE 4699 --- [http-nio-8080-exec-1282] o.s.w.s.m.StompSubProtocolHandler        : From client: SEND /spring-boot-web-jsp-1.0/app/chat session=ubdpn0zo
2019-09-27 00:37:03.797 TRACE 4699 --- [http-nio-8080-exec-1283] s.w.s.h.LoggingWebSocketHandlerDecorator : Handling TextMessage payload=[SEND
desti..], byteCount=115, last=true] in WebSocketServerSockJsSession[id=ubdpn0zo]
2019-09-27 00:37:03.798 TRACE 4699 --- [http-nio-8080-exec-1283] o.s.w.s.m.StompSubProtocolHandler        : From client: SEND /spring-boot-web-jsp-1.0/app/chat session=ubdpn0zo

Мой контроллер:

@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
    logger.error("MESSAGE HAS BEEN RECEIVED " + message.getText());
    String time = new SimpleDateFormat("HH:mm").format(new Date());
    return new OutputMessage(message.getFrom(), message.getText(), time);
}

Моя веб-конфигурация:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

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

Я попытался заменить отображение на:

@MessageMapping("app/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
    logger.error("MESSAGE HAS BEEN RECEIVED " + message.getText());
    String time = new SimpleDateFormat("HH:mm").format(new Date());
    return new OutputMessage(message.getFrom(), message.getText(), time);
}

Но все равно ничего.Я занимаюсь этим часами, и я не знаю, что еще делать, приложение отлично работает при работе на встроенном сервере Tomcat (и я соответствующим образом изменяю URL javascript).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...