春季简单的websocket项目返回200条代码

时间:2020-06-26 00:17:13

标签: spring websocket spring-websocket stomp

我构建了一个简单的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状态

你能帮我解决吗?

1 个答案:

答案 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连接。