stompspring-websocketjava-websocketstompjs

Can't establish connection between STOMPjs and Java Websocket using STOMP protocol


I followed this Spring Boot tutorial on Websockets implementing STOMP protocol which works perfectly on its own. I wanted to connect it to a frontend app which uses Expo so I am using STOMPjs

After setting up client and connecting I error: {"isTrusted": false, "message": "Failed to connect to localhost/127.0.0.1:8080"} so I can't establish a connection to my backend.

My backend is exactly as the guide:

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws");
    }
}

stompClient.ts

import { Client } from "@stomp/stompjs"
import 'text-encoding-polyfill';

export const stompClient = new Client({
    brokerURL: "ws://localhost:8080/ws",
    debug: (str) => {
        console.log(str);
    },
    onConnect(frame) {
        console.log("connected");
    },
    onStompError(error) {
        console.log(`stompError: ${error}`);
    },
    onWebSocketError(error) {
        console.log(error);
    },
    onDisconnect() {
        console.log("DISCONNECT");
    },
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000
})

stompClient.activate()

Two of the three open GitHub issues that are similar to mine have not yet been answered or updated bu OP

  1. Still seeing retry after a successful connection
  2. Connection keep closing on React Native

This one has one response which didn't work for me (add stompVersions to Client instance) 3. Not working in React Native

Any other ideas about what could be causing the failed connection error and how to solve it?


Solution

  • Had to change localhost in brokerUrl to actual ip address then follow this answer to establish a connection by adding the additional two lines seen below

        export const stompClient = new Client({
            brokerURL: "ws://YOUR_IP_ADDRESS:8080/ws",
            forceBinaryWSFrames: true,
            appendMissingNULLonIncoming: true,
            ...
        })