使用 Ionic App 中的 STOMP 连接到 ActiveMQ 代理

问题描述

我得到了一个 Ionic + Capacitor 应用程序,它将主要编译为在 Android 平台上运行。我的任务是将与远程 ActiveMQ 代理的通信集成到应用程序中。我使用 STOMP JS 库来实现这一点,当我在浏览器上测试它时,效果非常好。现在,当我在模拟器上测试时,应用程序无法连接到 ActiveMQ 代理。我相信这是因为浏览器支持开箱即用的 WebSockets,而模拟器无法理解 WS URL。我在网上读到我可以使用 SockJS 作为一个简单的解决方案,并且可以很容易地集成到我当前的代码中。我指的是以下教程:

https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/using-stomp-with-sockjs.html

但是,当我按照说明添加教程中提供的回退代码时,我收到了 Typescript 编译器抛出的一个奇怪的错误。我的代码如下:

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 WebScoket");
        // 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()

下面这行是抛出错误的地方:

client.webSocketFactory = new SockJS('http://localhost:61613/stomp');

编译器说“类型 'WebSocket' 不能分配给类型 '() => IStompSocket'。 类型 'WebSocket' 不匹配签名 '(): IStompSocket'。"

根据教程,看来我做对了。但是,Typescript 似乎认为存在一些不兼容。有没有人使用过 SockJS + STOMP 或我导入的任何库,并使其成功运行?任何线索将不胜感激!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)