如何解决尝试连接Websocket时使用“ SockJS + spring websocket”的Websocket错误404:未找到STOMP端点的路径
在我的Web应用程序中,我尝试使用SockJS连接到Websocket,但是返回了错误消息(找不到404路径“ / stomp / info”):
这个问题被问了很多遍,但是我找不到适合我情况的答案 有人可以帮助我找到解决方案吗?
这是我的代码
-基于spring网络流量,spring security(JWT)的服务器端[spring boot版本:2.1.2RELEASE]
WebSocketConfig.java
@Configuration
@EnableWebSocketMessagebroker
public class WebSocketConfig implements WebSocketMessagebrokerConfigurer {
@Override
public void configureMessagebroker(MessagebrokerRegistry registry) {
registry.enableSimplebroker("/prob");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/prob");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/stomp")
.setAllowedOrigins("http://localhost:4200")
//.setAllowedOrigins("*")
.withSockJS();
}
@Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setobjectMapper(new ObjectMapper());
converter.setContentTypeResolver(resolver);
messageConverters.add(converter);
return false;
}
}
CORSFilter.java
@Configuration
@EnableWebFlux
public class CORSFilter implements WebFluxConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders("Access-Control-Allow-Origin","Access-Control-Allow-Methods","Access-Control-Allow-Headers","Access-Control-Max-Age","Access-Control-Request-Headers","Access-Control-Request-Method")
.maxAge(3600)
.allowCredentials(false);
}
}
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@Configuration
public class WebSecurityConfig {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private SecurityContextRepository securityContextRepository;
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http
.cors().and().headers().frameOptions().disable().and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/login","/stomp","/stomp/**","/stomp/info","/stomp/info/**").permitAll()
.anyExchange().authenticated()
.and().build();
}
}
-基于Angular的客户端(stompjs + sockjs-client)
socketConnect() {
const socket = new SockJS('http://localhost:8081/stomp');
this.stompClient = StompJS.Stomp.over(socket);
const _this = this;
this.stompClient.connect({},function (frame) {
console.log('Connected: ' + frame);
_this.stompClient.subscribe('/prob/' + _this.id + '/newcomment',function (data) {
console.log(data);
});
});
}
更新
我更改了CORS过滤器的配置:
@Configuration
public class CORSFilter{
@Bean
CorsWebFilter corsWebFilter(){
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",config);
return new CorsWebFilter(source);
}
但是我仍然遇到其他错误:
获取http:// localhost:8081 / stomp / info?t = 1602859336795 404(未找到)
这是服务器端的websocket初始化日志:
2020-10-16 15:41:14.712 INFO 13060 --- [ restartedMain] o.s.m.s.b.SimplebrokerMessageHandler : Starting...
2020-10-16 15:41:14.712 INFO 13060 --- [ restartedMain] o.s.m.s.b.SimplebrokerMessageHandler : brokerAvailabilityEvent[available=true,SimplebrokerMessageHandler [DefaultSubscriptionRegistry[cache[0 destination(s)],registry[0 sessions]]]]
2020-10-16 15:41:14.714 INFO 13060 --- [ restartedMain] o.s.m.s.b.SimplebrokerMessageHandler : Started.
...
2020-10-16 15:42:13.750 INFO 13060 --- [Messagebroker-1] o.s.w.s.c.WebSocketMessagebrokerStats : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0),0 total,0 closed abnormally (0 connect failure,0 send limit,0 transport error)],stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-disCONNECT(0)],stompbrokerRelay[null],inboundChannel[pool size = 0,active threads = 0,queued tasks = 0,completed tasks = 0],outboundChannel[pool size = 0,sockJsScheduler[pool size = 1,active threads = 1,completed tasks = 0]
解决方法
最后我找到了问题, 问题是我为spring-mvc使用了websocket配置,而不是spring-webflux,我发现一个很好的tuto可以在spring-webflux的反应上下文中实现websocket:enter link description here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。