html Mqtt javascript客户端测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html Mqtt javascript客户端测试相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html>
<head>
	<title>Mqtt Client</title>
</head>
<body>
<input type="text" name="msg" id="msg" />
<input type="button" value="send" onclick="sendMsg()" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script type="text/javascript">
  var host = 'www.example.com';
  var port = Number(15675);
var client = new Paho.MQTT.Client(host, port, "/ws", "local_" + parseInt(Math.random() * 100, 10));
console.log(client);
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
    timeout: 30,
	keepAliveInterval: 10,
    onSuccess: function () {
        debug("CONNECTION SUCCESS");
        client.subscribe('order', {qos: 1});
    },
    onFailure: function (message) {
        debug("CONNECTION FAILURE - " + message.errorMessage);
    },
	onSuccess:onConnect,
	userName:"guest2",
	password:"guest2"
};

// connect the client
client.connect(options);
// 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('order', {qos: 1});
  //client.subscribe("order");
}

function debug(obj){
	console.log(obj);
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
	debug("CONNECTION LOST - " + responseObject.errorMessage);
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}
// called when a message arrives
function onMessageArrived(message) {
  debug("RECEIVE ON " + message.destinationName + " PAYLOAD " + message.payloadString);
  //print_first(message.payloadString);
  console.log("onMessageArrived:"+message.payloadString,new Date());
}

function sendMsg(){
	console.log("you have click");
	var text = document.getElementById("msg").value;
	var message = new Paho.MQTT.Message(text);
    message.destinationName = "order";
    client.send(message);
}
</script>
</body>

</html>

以上是关于html Mqtt javascript客户端测试的主要内容,如果未能解决你的问题,请参考以下文章

Linux C的MQTT测试代码编写 - 跨主机的MQTT客户端通信

MQTT协议-报文分析及网络客户端报文测试(MQTT报文连接阿里云上传数据+订阅数据)

MQTT协议-报文分析及网络客户端报文测试(MQTT报文连接阿里云上传数据+订阅数据)

Linux编程MQTT实现主题发布订阅

如何通过javascript 使用 MQTT

mqtt客户单和服务端进行测试