无法连接到 WebSocket 服务器(Spring)

4

我尝试使用Stomp(而不是SockJS)与Spring服务器和Angular客户端实现纯websocket。

这是我在Spring中启用websocket的代码:

@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {

    @Bean
    public TaskScheduler heartBeatScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker('/status')
                .setHeartbeatValue(new long[] { 10000, 10000})
                .setTaskScheduler(heartBeatScheduler());

        registry.setApplicationDestinationPrefixes('/');
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint('/myapp-websocket').setAllowedOrigins("*");
    }

    @Override
    protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
        messages.anyMessage().authenticated();
    }

    @Override
    protected boolean sameOriginDisabled() {
        return true;
    }
}

但是当我尝试使用stompjs在angular中连接时,无法连接。当我使用wscat wscat -c "ws://localhost:4200/api/myapp-websocket"进行测试时(/api/是正确的),没有响应,一直在尝试连接但没有成功。

这里出了什么问题?

编辑:这是我使用的两个依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-messaging</artifactId>
</dependency>

编辑:

我也试图将 messages.anyMessage().authenticated(); 更改为 messages.anyMessage().permitAll(); ,但依然无法连接到我的WebSocket。


你的控制台有错误吗?如果有,请提供它。 - Noureddine
控制台没有错误,我只有这个日志:Tue Feb 18 2020 14:58:29 GMT+0100 (heure normale d’Europe centrale) "Opening Web Socket...",然后连接从未打开。 - Spialdor
1个回答

3

我猜测您从不同的端口发送客户端请求,这意味着您的客户端位于不同的来源,因此您必须在服务器端添加一些标头。此外,在连接websocket时会向端点发送POST请求,您必须启用它。我不知道确切的端点是什么,请在控制台中检查,然后将它们添加到antMatchers中。

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
            .and()
            .csrf().disable().authorizeRequests()
            .antMatchers("/status**", "/topic", "/myapp-websocket/**")
            .permitAll()
            .anyRequest()
            .authenticated();

    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(ImmutableList.of("*"));
        config.setAllowCredentials(true);
        config.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        config.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

1
在configure方法中,您已经写了cors disable,那么为什么还需要corsconfiguration bean呢?目前我已经启用了cors,但是我无法连接到webscoket。如果我启用了cors,您能帮我做出哪些更改吗? - PramodA

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