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:
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 (
/wsin 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.
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
connectmethod if you haven't already—it’ll reveal hidden connection issues that the main console might not show. - An undefined
frameobject (the source of that "connected to server undefined" message) almost always points to a failed handshake.
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 Protocolsresponse. - 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:
(Avoid usingregistry.addEndpoint("/ws").setAllowedOrigins("https://your-frontend-domain.com").withSockJS();"*"in production—restrict it to your actual frontend domain.)
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
/appprefix will send messages directly to the message broker instead of your controller, which is why your endpoint isn’t processing them.
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

