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

使用stomp.js连接STOMP失败,无法接收消息求助

排查STOMP连接与消息接收问题

前端STOMP连接代码

var stompClient = Stomp.over(function () {
  return sock;
});

console.log("before con");

stompClient.connect({}, () => {
    setConnected;
    stompClient.subscribe("/topic/hello", (message) => {
        console.log(message);
    });
    console.log("runnable");
});

运行日志

LOG  before con
LOG  Opening Web Socket...
LOG  Web Socket Opened...
LOG  >>> CONNECT
accept-version:1.2,1.1,1.0
heart-beat:10000,10000

Spring Boot WebSocket配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
//        registry.addEndpoint("/ws").withSockJS();
        registry.addEndpoint("/ws").setAllowedOrigins("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

Postman测试情况

WebSocket连接正常,但发送CONNECT帧后未收到服务器回复,STOMP连接异常。发送的CONNECT帧内容:

CONNECT
accept-version:1.2
host:localhost

^@

排查与修复方案

  1. 修正前端回调语法错误
    代码中setConnected;是无效语句,若setConnected是切换连接状态的函数,需改为setConnected(true);。同时添加错误回调,捕获连接失败原因:

    stompClient.connect({}, () => {
        setConnected(true);
        stompClient.subscribe("/topic/hello", (message) => {
            console.log(message);
        });
        console.log("runnable");
    }, (error) => {
        console.error("STOMP连接失败:", error);
    });
    
  2. 确认WebSocket端点地址正确性
    检查前端sock变量对应的WebSocket地址是否为ws://localhost:端口号/ws,若Spring Boot使用非默认8080端口,必须指定端口。

  3. 完善Postman的CONNECT帧格式
    host字段需填写完整主机+端口(如host:localhost:8080),且帧结尾必须包含空行和NULL字节(^@),确保符合STOMP协议规范。

  4. 开启Spring Boot调试日志
    在application.properties中添加日志配置,查看STOMP握手细节:

    logging.level.org.springframework.messaging=DEBUG
    logging.level.org.springframework.web.socket=DEBUG
    

    日志会显示是否存在握手失败、版本不兼容或其他异常。

  5. 检查跨域与拦截器
    若前端与后端存在跨域,当前setAllowedOrigins("*")配置在测试环境有效,但需确认是否有其他拦截器(如Spring Security)阻止了WebSocket请求,必要时添加WebSocket的权限放行规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 20:03:12