【问题标题】:Spring simple websocket project returns 200 codespring简单websocket项目返回200代码
【发布时间】:2020-06-26 00:17:13
【问题描述】:

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

你能帮我解决一下吗?

【问题讨论】:

    标签: spring websocket spring-websocket stomp


    【解决方案1】:

    在 WebSocketConfig.java 中,您已将端点配置为 /ws -

    registry.addEndpoint("/ws")
                    .withSockJS();
    

    在从 typescript 前端连接到 websocket 端点时,请执行此操作 -

    let ws = new SockJS("http://localhost:8080/ws") ;  // localhost:8080 can be your backend endpoint
    this.stompClient = Stomp.over(ws);
    

    当使用 sockjs 库时,我们必须通过 http 协议进行连接,然后库在内部管理 WS 连接。

    【讨论】:

    • 你的问题?
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2017-08-06
    • 2017-01-29
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多