You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React WebSocket无法订阅Spring Boot后端WebSocket主题问题

问题排查与解决方案

后端配置检查

  • 确保Spring Boot的WebSocket配置类正确启用STOMP并支持/topic前缀:
    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            // 启用简单消息代理,支持/topic前缀的广播
            config.enableSimpleBroker("/topic");
            // 若有应用前缀需求,比如/app,可按需添加
            // config.setApplicationDestinationPrefixes("/app");
        }
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            // 注册WebSocket端点,允许SockJS降级兼容
            registry.addEndpoint("/websocket").withSockJS();
        }
    }
    
  • 检查Spring Security配置,放行WebSocket相关路径:
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/websocket/**").permitAll()
                // 其他权限规则...
            );
        return http.build();
    }
    

前端代码修正

你导入了SockJS但未实际使用,Spring Boot默认的WebSocket端点通常支持SockJS降级,直接用原生WebSocket可能出现协议或路径不匹配,修改客户端初始化逻辑:

import { Client, Stomp } from '@stomp/stompjs';
import { Button, Stack } from '@mui/material';
import SockJS from 'sockjs-client';

const topic = '/topic/messages';

const WS_URL = 'http://103.173.155.***:8080/websocket'; // 使用HTTP前缀,SockJS自动处理协议转换

export default function TextSection() {
  const stompClient = Stomp.over(() => new SockJS(WS_URL));
  
  stompClient.onConnect = () => {
    console.log('Connected, Hello World');
    // 新增订阅错误捕获
    stompClient.subscribe(topic, 
      (message) => console.log(`Received: ${message.body}`),
      (error) => console.error('订阅失败:', error)
    );
  };

  stompClient.onStompError = (frame) => {
    console.error(`Broker报错: ${frame.headers.message}`);
    console.error(`详情: ${frame.body}`);
  };

  stompClient.onWebSocketError = (error) => {
    console.error('WebSocket错误', error);
  };

  const connect = () => {
    stompClient.connect({}, () => console.log('连接成功'));
  };

  const disconnect = () => {
    stompClient.deactivate();
  };

  return (
    <Stack sx={{ minHeight: '100vh' }}>
      <Button onClick={connect} variant="contained">Connect</Button>
      <Button onClick={disconnect} variant="contained">Disconnect</Button>
    </Stack>
  );
}

调试手段

  • 后端开启DEBUG日志,查看STOMP请求细节:
    在application.properties中添加:
    logging.level.org.springframework.messaging=DEBUG
    logging.level.org.springframework.web.socket=DEBUG
    
  • 前端查看浏览器控制台的订阅错误信息,结合后端日志定位问题。

跨域检查

如果前后端跨域,确保后端配置CORS支持:

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*"); // 生产环境替换为具体域名
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

内容的提问来源于stack exchange,提问作者Arthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:10:24