HTML文件中引入mqtt.js文件下载地址
var client = mqtt.connect('ws://localhost:3000');
// 客户端连接成功
client.on('connect', function () {
.....
});
// 客户端连接失败
client.on("error", function (error) {
console.log(error);
});
// 客户端收到消息
client.on("message", function (topic, payload) {
console.log("主题:" + topic + ", 消息:" + payload.toString());
});
注意事项:
先启动代理服务器broker,这是采用的是Mosca,相关代码:
var mosca = require("mosca");
var ascoltatore = {
};
var settings = {
port: 1883,
backend: ascoltatore,
http:{
port:3000,
bundle:true,
static:'./'
}
};
var server = new mosca.Server(settings);
// fired when the mqtt server is ready
server.on('ready',function(){
console.log('Mosca Server is up and running ....');
});
// fired when a message is received
server.on('published',function(packet,client){
var topic = packet.topic;
var buffer = packet.payload;
console.log("topic:" + topic + ",message:", buffer);
});
server.on('subscribed',function(topic,client){
console.log("subscribed:", topic);
});
server.on('unsubscribed',function(topic,client){
console.log("unsubcribed:", topic);
});
server.on('clientConnected',function(client){
var clientId = client.id;
console.log('client connected:',clientId);
});
server.on('clientDisconnected',function(client){
console.log('client disConnected:',client.id);
});