How to work with websockets in react js and spring boot application

28 Views Asked by At

I'm trying to connect with web socket which is on spring boot via React JS but not able to establish connection I'm using the stompJS and sockjs-client libraries from npm It's working while tested on local machine but when deployed on Ubuntu server it's not connecting The front end and back end both are on same server

Here is the code for ReactJs

import SockJS from 'sockjs-client';
import { over } from 'stompjs';

const connect = () => {
    const sock = new SockJS('/ws-endpoint');
    const temp = over(sock)
    setStompClient(temp);

    temp.connect({}, onConnected,onError)
}

const onError = (error) => {
    console.log('error: ', error);
}

const onConnected = (frame) => {
    console.log('frame: ', frame);
    console.log('Connected');
    setIsConnected(true);
}
const onMessageReceived = (payload) => {
    console.log('PayLoad:',payload.body);
    if(payload.body === 'REFRESH')  handleForceRerender();
}

useEffect(() => {
    connect();
}, [])

useEffect(() => {
    if(isConnected && stompClient)  {
        const subscription = stompClient?.subscribe('/topic/notification', onMessageReceived)
        console.log('Subscribe called:');
        return () => {
            subscription?.unsubscribe();
        }
    }
})
0

There are 0 best solutions below