我试图在覆盆子上的一个MQTT Broker上发布消息。 我已经建立了一个应用程序"使用visual studio 2015(在Windows 10上),我使用涟漪模拟器测试它,但我总是得到这个错误
AMQJS0011E无效状态未连接。
我还尝试导出文件,并在Linux系统上使用firefox打开它们作为常规网页,我得到了同样的错误,所以我不认为是与Windows相关的东西。
使用按钮触发的功能是playCanzone()
function playCanzone() {
console.log("play premuto");
mqttHost = '192.168.9.184';
topic = 'testTopic';
client = new Paho.MQTT.Client(mqttHost, 8080, "myclientid_" + parseInt(Math.random() * 100, 10));
onConnect();//publish('mEssaggio', 'testtopic/bar', 2);
}
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({ onSuccess: onConnect });
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe(topic);
message = new Paho.MQTT.Message("Hello");
message.destinationName = topic;
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}
答案 0 :(得分:4)
您尝试在连接打开前发送内容。
这应该表现得更好并确保一切按顺序发生
var client; topic;
function playCanzone() {
console.log("play premuto");
var mqttHost = '192.168.9.184';
topic = 'testTopic';
client = new Paho.MQTT.Client(mqttHost, 8080, "myclientid_" + parseInt(Math.random() * 100, 10));
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({ onSuccess: onConnect });
}
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe(topic);
var message = new Paho.MQTT.Message("Hello");
message.destinationName = topic;
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}