Simple use of mqtt

The server communicates with the browser. The server needs to establish a mosca service and an http service. The browser connects to the http service port.

Service-Terminal:

method one:

var fly = require ('fly');  
var MqttServer = new mosca.Server ({  
    port: 2000,
    http: {
        port: 3006,
        bundle: true,
        static: './'
        }
});

  
MqttServer.on('clientConnected', function(client){  
    console.log('client connected', client.id);  
});  
  
/**
 * Listen for MQTT topic messages
 **/  
MqttServer.on('published', function(packet, client) {  
    var topic = packet.topic;  
    console.log('message-arrived--->','topic ='+topic+',message = '+ packet.payload.toString());  
   //MQTT forwards topic messages
   //MqttServer.publish({topic: 'test', payload: 'sssss'});
});  
  
MqttServer.on('ready', function(){  
    console.log('mqtt is running...');  
    //MqttServer.authenticate = authenticate;  
});  

  Method two:

var http     = require('http')
  , httpServ = http.createServer()
  , fly = require ('fly')
  , mqttServ = new mosca.Server({port: 2000});

mqttServ.attachHttpServer(httpServ);

httpServ.listen(3006);
MqttServer.on('clientConnected', function(client){  
    console.log('client connected', client.id);  
});

  Browser client:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        <div>hello mqtt</div>
        <script src="../public/js/jquery-1.9.1.min.js"></script>
    
        <script src="../public/mqtt.min.js"></script>
        <script>
           var client = mqtt.connect('ws://localhost:3006',{ //The port is the http port mqtt://localhost:3006 is the same as ws://localhost:3006                                                              

}); // you add a ws:// url here
             client.subscribe("mqtt/demo"); 
client.on('connect', function () {
console.log('connected.....');
});
client.on("message", function (topic, payload) {
alert([topic, payload].join(": "));
})
client.publish("mqtt/demo", "hello world!");

</script>
</body>
</html>

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325145462&siteId=291194637
Recommended