这个是 mqtt 的服务 nodejs 代码
const mosca = require('mosca')
const MqttServer = new mosca.Server({
port: 8081
})
MqttServer.on('clientConnected', function(client){
console.log('client connected', client.id);
console.log('客户端连接成功啦啦啦');
});
这个是 node 的客户端代码,访问正常
let mqtt = require('mqtt')
let options = {
}
let client = mqtt.connect('mqtt://127.0.0.1:8081', options)
client.on('connect', function (res) {
console.log(res)
})
以下是前端代码,访问失败
<meta charset="UTF-8">
<html>
<head>
<title> QBB IM WebSocket Example</title>
<style></style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type ="text/javascript">
</script>
<script type="text/javascript" language="javascript">
var mqtt;
var reconnectTime=1000;
// var host="192.168.1.20"; // ws://apiimtest.qbb6.com
var host="127.0.0.1";
var port= 8081;
function onConnect(){
console.log("connected");
message = new Paho.MQTT.Message("Hello World");
mqtt.send(message);
}
function onFailure(){
console.log("onFailure");
}
function MQTTConnect(){
console.log("connecting to "+host+" "+port);
// console.log(new Paho())
mqtt = new Paho.MQTT.Client(host, port, "clientjs");
var options={
// timeout:3,
useSSL: false,
onFailure: onFailure,
onSuccess:onConnect
};
mqtt.connect(options);
console.log("oo")
}
</script>
</head>
<body>
<h1>Main Body</h1>
<script>
MQTTConnect();
</script>
</body>
</html>
1
chenlaocong OP 怎么在客户端看的不是 markdown 啊😯😯
|