Open Penergy opened 8 years ago
How are you configuring your express server? You need to serve the mqtt.js client.
This is my express configuration:
var app = require('../app');
var debug = require('debug')('mqttSV:server');
var http = require('http');
var mqttsv = require('../mqttsv.js').getServer(); // pengyc
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Create MQTT server.
*/
mqttsv.attachHttpServer(server);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, function(err){
if(err) throw err;
console.log("Server is running!");
});
mqttsv.js-part
var mosca = require("mosca");
var server;
var ascoltatore = {
//using ascoltatore
type: 'mongo',
url: 'mongodb://localhost:27017/mqtt',
pubsubCollection: 'ascoltatori',
mongo: {}
};
var moscaSettings = {
// port: 1883,
interfaces:[
{type:"mqtt", port: 1883},
// {type:"mqtts", port:8883, credentials:{keyPath:SECURE_KEY,certPath: SECURE_CERT}},
],
backend: ascoltatore,
logger:{
name: "secureExample",
lebel: 40,
},
persistence: {
factory: mosca.persistence.Mongo,
url: 'mongodb://localhost:27017/mqtt'
},
// secure: {
// keyPath: SECURE_KEY,
// certPath: SECURE_CERT,
// }
};
var Mqttsv = function(){
server = new mosca.Server(moscaSettings);
server.on('ready', setup);
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
// fired when a message is received
server.on('published', function(packet, client) {
console.log('Published', packet);
});
// when client return puback,
server.on('delivered', function(packet, client){
console.log('Delivered', packet);
});
}
/*
* Module exports
*/
module.exports = new Mqttsv();
Mqttsv.prototype.getServer = function(){
return server;
}
function setup() {
console.log('Mosca server is up and running')
}
If you configure express in this way, you need to serve MQTT.js yourself.
You can grab a working copy for the browser in node_modules/mosca/public/mqtt.js
.
Following your suggestion, it works. Thank you very much.
What's more, I used socketio once and it can import socketion.js
from node_modules/socketio
folder. What's the difference in your code?
Because I did it this way. It's more production-oriented.
I tried to build a service by using MQTT over websocket and followed the link: MQTT-over-Websocket.
However, the following script is not founded:
<script src="/mqtt.js"></script>
How can I create a web client using mqtt.js? By the way, I use ExpressJS.