I was trying to connect to the remote only one time when the page loaded and subscribe channels afterwards when necessary.
To ensure the code can be shared by different pages, I wrote the code (closure) as follows and export the function webSocket
as this:
export function webSocket() {
const socket = new SockJS(WebSocketEndPoint.RESOURCE_CONTROLLER);
const stompClient = Stomp.over(socket);
let isConnected = false;
function subscribe(address, callback) {
if (isConnected) {
stompClient.subscribe(address, callback);
} else {
stompClient.connect({}, () => {
isConnected = true;
stompClient.subscribe(address, callback);
});
}
};
function subscribeRealtimeExecOutput(addr, callback){
subscribe(addr, callback);
}
return {
subscribeRealtimeExecOutput,
};
}
And
Use it in other pages as follows:
import { webSocket } from '../../websocket/websocketService';
//in the constructor
this.subscriber = webSocket().subscribeRealtimeExecOutput;
//used when required
this.subscriber(pane.jobIdentifier, (data) => {
console.log(data);
});
And I hope the connect
method will only be run once within the same page and the subscriber will then subscribe different channels based on the connection.
But, it seems it won't work - the connection will not be set up and consequently the browser just prompt me about Opening Web Socket...
Anyone can help? Thank you so much for your help.
Sincerely, Hearen