我构建了一个简单的websocket项目(位于localhost:4000)
WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/topic");
}
}
SecurityConfig.java
http
.cors().and()
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/ws/**").permitAll() // Permit ws connection
.anyRequest().authenticated()
.and()
.apply(new JwtConfigurer(jwtTokenProvider));
// cors config below
之后,尝试从位于localhost:3000的客户端进行连接。 并获得200状态而不是101状态。
import { Stomp, Client } from '@stomp/stompjs';
let client = new Client({
brokerURL: "ws://localhost:4000/ws"
})
client.activate()
服务器回复标头Connection: keep-alive
而不是Connection: Update
并返回200状态
你能帮我解决吗?
答案 0 :(得分:0)
在WebSocketConfig.java中,您已将端点配置为/ ws-
registry.addEndpoint("/ws")
.withSockJS();
从打字稿前端连接到websocket端点时,请执行此操作-
let ws = new SockJS("http://localhost:8080/ws") ; // localhost:8080 can be your backend endpoint
this.stompClient = Stomp.over(ws);
使用sockjs库时,我们必须通过http协议进行连接,然后在内部由该库管理WS连接。