Reputation: 1000
This is my simple attempt to create a WebSocket channel between a JavaScript client and a Java server.
// java websocket server configuration with spring boot
// server port: 8080 set in the "application.yml"
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app")
.enableSimpleBroker("/notification");
}
}
// js websocket client configuration with "webstomp-client"
import webstomp from 'webstomp-client';
const connection = new WebSocket('ws://localhost:8080/websocket');
const stompClient = webstomp.over(connection);
stompClient.connect(()=>{
stompClient.subscribe('/app/notification', () => console.log('Connection established with server'));
});
The console shows the following:
WebSocket connection to 'ws://localhost:8080/websocket' failed: Error during WebSocket handshake: Unexpected response code: 200
I looked at a lot of other posts, and most of them had to do with allowing the origin. I have tried setting the origin to localhost
as well as the local IP address, but without success.
What am I missing? Any help would be tremendous.
Edit: The client is created with create-react-app
, if that's relevant.
Edit: The client is on: http:localhost:3000
, the server is on: http:localhost:8080
.
Upvotes: 3
Views: 3458
Reputation: 8414
You are configuring your endpoint with SockJS on the server side but you are not using SockJS on the client side. That's why you get a 200 status code instead of a 101. Either use SockJS on the client side (instead of a raw WebSocket) or remove withSockJS()
on the server side.
Upvotes: 4