I've recently received an Ionic + Capacitor app that is primarily meant to run on the Android platform. My current task is to incorporate communication with a remote ActiveMQ broker into the app. To achieve this, I utilized the STOMP JS library which works seamlessly when tested on the browser. However, encountering connectivity issues when testing on the emulator led me to believe that the problem lies in the emulator's inability to understand the WS URL, unlike the browser which supports WebSockets by default. Researching online, I came across using SockJS as a potential simple solution and found a tutorial that may help in integrating it smoothly into my existing code:
Following the instructions provided in the tutorial and adding the fallback code resulted in encountering a strange error thrown by the Typescript compiler. Here is a snippet of my code:
import {Client, Message, ActivationState, messageCallbackType} from '@stomp/stompjs'
//import StompJs, { Message } from '@stomp/stompjs';
import { Queue } from 'queue-typescript';
import SockJS from 'sockjs-client';
const brokerEndpoint = "ws://localhost:61614";
//const brokerEndpoint = "ws://10.0.2.2:61614";
const items: string[] = [];
const queue = new Queue<string>(...items);
const createClient = () => {
const client: Client = new Client({
brokerURL: brokerEndpoint,
connectHeaders: {
login: 'admin',
passcode: 'admin',
},
debug: function (str) {
console.log(str);
},
reconnectDelay: 1000,
heartbeatIncoming: 0,
heartbeatOutgoing: 0
});
client.webSocketFactory = new SockJS('http://localhost:61613/stomp');
/*
if (typeof WebSocket !== 'function') {
console.log("Not WebSocket");
// For SockJS you need to set a factory that creates a new SockJS instance
// to be used for each (re)connect
client.webSocketFactory = function () {
// Note that the URL is different from the WebSocket URL
return new SockJS('http://10.0.2.2:15674/stomp');
};
} else {
console.log("Still using WebSockets");
}
*/
return client;
}
const client: Client = createClient()
The error is triggered at the following line:
client.webSocketFactory = new SockJS('http://localhost:61613/stomp');
The compiler indicates that "Type 'WebSocket' is not assignable to type '() => IStompSocket'. Type 'WebSocket' provides no match for the signature '(): IStompSocket'."
Despite following the tutorial, there appears to be a conflict according to Typescript. Anyone who has experience working with SockJS + STOMP or any of the imported libraries successfully? Any assistance would be highly valued!