简体   繁体   中英

WebSocket with Spring Boot and JavaScript

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 .

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.

console.log("IDK") // idk to be honest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM