作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试使用 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/
我正在开发一个 voip 调用应用程序。我需要做的是在接到来电时将 Activity 带到前台。我在应用程序中使用 Twilio,并在收到推送消息时开始调用。 问题是我试图在接到任何电话时显示 Act
我是一名优秀的程序员,十分优秀!