是否可以使用websockets和cloudmqtt? 我有以下代码,但没有任何工作。 首先,我使用Paho的mqttw31.js,在我的主机文件中,我定义了所有的连接细节。
src="js/mqttws31.js" type="text/javascript">
src="js/host.js" type="text/javascript">
var mqtt;
var reconnectTimeout = 2000;
function MQTTconnect() {
mqtt = new Paho.MQTT.Client(
host,
port,
"web_" + parseInt(Math.random() * 100,
10));
var options = {
timeout: 3,
useSSL: useTLS,
cleanSession: cleansession,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
if (username != null) {
options.userName = username;
options.password = password;
}
console.log("Host="+ host + ", port=" + port + " TLS = " + useTLS + " username=" + username + " password=" + password);
mqtt.connect(options);
}
function onConnect() {
$('#status').val('Connected to ' + host + ':' + port);
// Connection succeeded; subscribe to our topic
mqtt.subscribe(topic, {qos: 0});
$('#topic').val(topic);
mqtt.publish("/arduino/commando/", "test Intel");
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
var payload = message.payloadString;
$('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
};
$(document).ready(function() {
MQTTconnect();
});
<header>
<h2>MQTT Test</h2>
</header>
<div>
Subscribed to <input type='text' id='topic' disabled />
Status: <input type='text' id='status' size="80" disabled />
<ul id='ws' style="font-family: 'Courier New', Courier, monospace;"></ul>
</div>
在主机文件中:
host = 'm20.cloudmqtt.com'; // hostname or IP address
port = 13365;
topic = '/arduino/status/'; // topic to subscribe to
useTLS = false;
username = "test";
password = "test";
cleansession = true;
答案 0 :(得分:0)
快速浏览一下cloudmqtt.com doc并没有提到任何地方的websockets。
假设他们正在运行Mosquitto 1.4,那么本地MQTT和MQTT不会使用相同的端口而不是websockets,所以如果他们只为你提供1个端口号,那么它真的不会起作用。
答案 1 :(得分:0)
使用端口33365并将useTLS设置为true。