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

时间:2020-02-18 10:30:23

标签: java spring websocket spring-websocket stomp

我尝试通过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();,但仍然无法连接到我的网络套接字。

1 个答案:

答案 0 :(得分:1)

我想您从不同的端口发送客户端请求,这意味着您的客户端来自不同的源,因为您必须在服务器端添加一些标头。同样,在连接上,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;
        }
}