gpt4 book ai didi

java - 无法连接到 websocket 服务器(spring)

转载 作者:行者123 更新时间:2023-12-02 08:59:21 26 4
gpt4 key购买 nike

我尝试使用 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 进行角度连接时,连接从未完成。当我使用 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..

最佳答案

我想您从不同的端口发送客户端请求,这意味着您的客户端位于不同的源,因此您必须在服务器端添加一些 header 。此外,在连接时,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;
}
}

关于java - 无法连接到 websocket 服务器(spring),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60278791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com