使用SockJs切换Spring Websocket从XHR流式传输到Websocket

4

我正在使用Spring Websocket与SockJs (v1.1.1)在客户端上进行STOMP通信。我使用以下代码创建客户端。

SockJS = require('sockjs-client')
Stomp = require('webstomp-client')
stompClient = Stomp.over(new SockJS(url))

它工作得很好。但是默认使用 xhr_streaming 作为传输方式,这对我来说并不理想。我想将其切换到 websocket 传输方式。

stompClient = Stomp.over(new SockJS(url, null, {transports:'websocket'}))

但是这种方法对我不起作用。它会出现事件错误:
code: 2000
reason: "All transports failed"

我的Spring Websocket配置非常简单:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> {

    @Override
    public void configureStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/myEndpoint").setAllowedOrigins("*")
            .withSockJS();
    }

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

}

我使用xhr_streaming时遇到的主要问题是每个流请求都会更新用户会话的最后访问时间(我也使用Spring Session)。但这不是我的应用程序所期望的行为。那么我该如何解决呢?使用websocket传输方式可以帮助吗?谢谢。

1个回答

4

所以,我找到了原因。我正在使用webpack开发服务器,并使用proxy选项。默认情况下,它不会代理ws协议请求(它会丢失头信息)。您需要在配置中添加ws: true,然后一切都会正常工作。

proxy: {
        '/api/*': {
            target: 'http://localhost:8080',
            pathRewrite: {'^/api' : ''},
            ws: true 
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接