1

I´m trying to implement a websocket in my spring boot application, but I´m unable to create a connection.

I used this video and its corresponding git-repo to create the following config for the server and the javascript code for the client.

Server

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gameplay");
        registry.addEndpoint("/gameplay").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

Client

const url = 'http://localhost:8080';
let stompClient;
let paymentId;

function connectToSocket() {
    console.log("Trying to open connection to /gameplay");
    let socket = new SockJS("/gameplay");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("connected to the frame: " + frame);
        stompClient.subscribe("/topic/game-progress", function (response) {
            console.log("data");
            let data = JSON.parse(response.body);
            console.log(data);
        })
    })
}

The server-console doesn´t have any entries, so I guess there is something wrong with the javascript part. In the browser-console it says:

Trying to open connection to /gameplay
Opening Web Socket...
GET http://localhost:8080/gameplay/info?t=1620312392571 404
Whoops! Lost connection to http://localhost:8080/gameplay

I tried...

  1. using different URLs to establish the connection
    • http://localhost:8080/gameplay
    • http://localhost:8080/app/gameplay
    • /gameplay
    • /app/gameplay
  2. Using the URLs from the first bullet point to establish a connection using Chrome´s advanced REST client. I got the message "Unknown error occured"
  3. Adding .setAllowedOrigins("*") to my stompEndpointRegistry like suggested here

Does anyone know...

  1. Where the last part of the request (/info?t=1620312392571 )comes from and could it be causing the malfunction?
  2. If I need to write "http:localhost.8080" before the socket URL? Some people do that, others don´t.
  3. How I can get this working?

In others questions the root of the problem had something to do with the dependencies. I included all the dependencies that fixed the problem for other users so I. don´t think the dependencies are the problem. However, here is a link to my pom.xml.

I´m thankful for all kind of help.

Greta
  • 300
  • 1
  • 10

1 Answers1

0

I was also facing same issue. Update client code as

let socket = new SockJS("/app/gameplay");

Don't modify below server code

registry.addEndpoint("/gameplay").withSockJS();
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36