无法连接到websocket服务器(春季)

问题描述 投票:0回答:1

我尝试通过Spring服务器和Angular客户端使用Stomp(而不是SockJs)实现普通的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进行连接时,连接从未完成。当我用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。

java spring websocket spring-websocket stomp
1个回答
0
投票

我想您从其他端口发送客户端请求,这意味着您的客户端来自不同的源,因为您必须在服务器端添加一些标头。同样在连接时,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;
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.