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

SpringBoot WebSocket服务端连接成功后无响应如何排查解决

问题解决方案

你代码中存在多处路径不匹配、格式错误的问题,按以下步骤修改即可:

1. 修复WebSocket配置类前缀不匹配问题

你配置的简单消息代理前缀为/topics,但@SendTo注解使用的是/topic前缀,二者不一致导致消息无法正常推送:

@Override
public void configureMessageBroker(MessageBrokerRegistry registry){
    // 修改为/topic 和@SendTo前缀保持一致
    registry.enableSimpleBroker("/topic");
    registry.setApplicationDestinationPrefixes("/app");
}

2. 修复Controller路径大小写不匹配问题

@MessageMapping配置的路径是大写开头的/Hello,但前端请求的是小写/hello,Spring WebSocket路径大小写敏感,修改为统一小写即可:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public  Greeting greeting(HelloMessage message){
    return new Greeting("Hello, "+ HtmlUtils.htmlEscape(message.getName()));
}

3. 修复前端连接、订阅路径错误

STOMP协议通信不需要在订阅、发送消息时携带完整域名端口,你已经在初始化SockJS时指定了服务端地址,且路径中多余的双斜杠也会导致匹配失败:

function connect() {
    // 去掉多余的斜杠
    var socket = new SockJS('http://localhost:8080/stomp-endpoint');
    stompClient = Stomp.over(socket);
    // 可选:关闭多余的debug日志,解决connected to server undefined提示
    stompClient.debug = null;
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        // 订阅路径改为相对路径,不需要带域名端口
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body));
        });
    });
}

4. 修复前端消息发送路径错误

去掉发送路径中的域名、端口,直接使用应用前缀+接口路径即可:

function sendName() {
    stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}

修改完成后重启后端服务,刷新前端页面即可正常收发消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:54:03