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

Spring WebSocket(Spring 4)订阅通知失效问题排查求助

Hey there, let's break down what might be going on with your Spring 4 WebSocket/STOMP setup. That "connected to server undefined" message is a big clue—usually it means the STOMP client isn't properly completing the handshake with your backend. Here are the most common fixes to check:

1. Verify Spring WebSocket Endpoint Configuration

First, double-check your Spring config (Java or XML) to ensure the STOMP endpoint is set up correctly. For Java-based config, it should look like this:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }
}
  • Confirm the endpoint path (/ws in this example) matches exactly what your client is trying to connect to.
  • If you're using SockJS, make sure you've included the SockJS client library in your HTML file.
2. Fix the STOMP Client Connection Code

That "connected to server undefined" error often pops up when the client's connection URL is incorrect or the handshake fails. Your client JS should look similar to this:

var socket = new SockJS('/ws');
var stompClient = Stomp.over(socket);

stompClient.connect({}, function(frame) {
    console.log('Connected successfully: ' + frame);
    // Add your topic subscriptions here
}, function(error) {
    console.error('Connection failed: ' + error);
});
  • If your app is deployed under a context path (like /my-project), update the SockJS URL to include it: new SockJS('/my-project/ws').
  • Add the error callback to the connect method if you haven't already—it’ll reveal hidden connection issues that the main console might not show.
  • An undefined frame object (the source of that "connected to server undefined" message) almost always points to a failed handshake.
3. Inspect Network Traffic in Chrome DevTools

Open Chrome DevTools (F12), go to the Network tab, and filter by WS (WebSocket):

  • Look for the initial GET request to your SockJS endpoint—it should return a 200 status code.
  • Check if the WebSocket upgrade succeeds: you should see a 101 Switching Protocols response.
  • A 404 error means your client and Spring config are using mismatched endpoint paths.
  • If you see a CORS error, update your Spring endpoint to allow cross-origin requests:
    registry.addEndpoint("/ws").setAllowedOrigins("https://your-frontend-domain.com").withSockJS();
    
    (Avoid using "*" in production—restrict it to your actual frontend domain.)
4. Validate Message Sending Paths

When sending messages from the client, you must use the application prefix defined in your Spring config (/app in the example above). For instance:

stompClient.send("/app/chat-message", {}, JSON.stringify({content: 'Hello!'}));
  • Your Spring controller should map to this path with @MessageMapping:
    @Controller
    public class ChatController {
        @MessageMapping("/chat-message")
        @SendTo("/topic/chat-room")
        public ChatMessage handleIncomingMessage(ChatMessage message) {
            return message;
        }
    }
    
  • Forgetting the /app prefix will send messages directly to the message broker instead of your controller, which is why your endpoint isn’t processing them.
5. Enable Spring Debug Logging

Turn on debug logging for Spring WebSocket and messaging modules to uncover hidden issues. Add these lines to your application.properties or log4j.properties:

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

This will log detailed information about connection attempts, message routing, and any backend errors that aren’t showing up in the browser console.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:22:26