我有一个使用 Paho MQTT Javascript“mqttws31.js”的 Worklight 项目。
在模拟器中,一切正常,但是当从设备连接时,它总是给我一个超时。
当我通过设备上名为“MyMQTT”的应用程序连接到代理时,它连接正常。我无法让它与 JavaScript 一起工作。
我测试了此代码是否支持 websockets - Link 应用程序中的 webview 支持 websockets,因此这不可能是问题。
我尝试了几种连接选项,但总是超时。
我需要添加一些 Android 权限吗?
我添加了下面我尝试过的示例之一。
我使用的代理是 HiveMQ,并且我在端口 8000 上启用了 websocket 支持。
我还尝试连接到公共(public)经纪人 - test.mosquitto.org”,80 但这给了我相同的结果(在模拟器中工作,而不是在设备上)。
请帮助我!
我知道 Cordova 插件会比 Javascript 版本更好,但我没有找到 Cordova 3.1 的 Cordove MQTT 插件。这可以帮助我。
<小时/> var client = new Messaging.Client("192.168.137.2", 8000, "prototype2");
$(function() {
$("#publishBtn").click(function() {
publish("test", "prototype2/testpublish", 1);
});
var options = {
// connection attempt timeout in seconds
timeout : 5,
// Gets Called if the connection has successfully been established
onSuccess : function() {
$("#console").append(
'<br/>' + "Connected to MQTT Broker over Websockets.");
// client.subscribe("testtopic", {qos: 2});
client.subscribe("prototype3/testpublish");
},
// Gets Called if the connection could not be established
onFailure : function(message) {
$("#console").append(
'<br/>' + "Connection failed: " + message.errorMessage);
}
};
// Gets called whenever you receive a message for your subscriptions
client.onMessageArrived = function(message) {
var topic = message.destinationName;
var message = message.payloadString;
$("#console").append(
'<br/>' + 'Message arrived: Topic: ' + topic + ', Message: '
+ message);
};
// Attempt to connect
client.connect(options);
});
最佳答案
对于Android 4.3及更低版本,您需要cordova插件来提供WebSockets。其中有很多,但大多数都没有实现 MQTT 所需的功能(支持子协议(protocol)和二进制消息)
其中一个是:https://github.com/mkuklis/phonegap-websocket 。使用该插件,mqttws31.js 在 Android 4.3 上运行良好。
目前在 Worklight 6.1 中安装标准 Cordova 3 插件存在问题,这意味着当您将插件添加到项目中时,您需要编辑 Github 上提供的 JavaScript。编辑很简单,只需将:require()更改为:cordova.require()
关于javascript - Worklight - Paho MQTT JavaScript : Always timeout on Android device and works in simulator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22119017/