我只是在玩mqtt & mosca
我遵循了以下步骤:
npm install -g browserify // install browserify
cd node_modules/mqtt
npm install . // install dev dependencies
browserify mqtt.js -s mqtt > browserMqtt.jsindex.html
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script src="./browserMqtt.js"></script>
<script>
var client = mqtt.connect({ host: 'localhost', port: 1884 });
client.subscribe("presence");
client.on("message", function(topic, payload) {
console.log([topic, payload].join(": "));
client.end();
});
client.publish("presence", "hello world!");
</script>
</body>
</html>server.js
var mosca = require('mosca')
//1883
var settings = {
port: 1884
};
//here we start mosca
var server = new mosca.Server(settings);
server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
console.log('Mosca server is up and running')
}
// fired whena client is connected
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 MIO: ', packet.payload);
});
// fired when a client subscribes to a topic
server.on('subscribed', function(topic, client) {
console.log('subscribed : ', topic);
});
// fired when a client subscribes to a topic
server.on('unsubscribed', function(topic, client) {
console.log('unsubscribed : ', topic);
});
// fired when a client is disconnecting
server.on('clientDisconnecting', function(client) {
console.log('clientDisconnecting : ', client.id);
});
// fired when a client is disconnected
server.on('clientDisconnected', function(client) {
console.log('clientDisconnected : ', client.id);
});但如果我跑了
node server在我访问我的index.html时,我没有在运行服务器的控制台窗口中看到任何消息。
用这个(完全一样)我可以看到这个信息
client.js
var mqtt = require('mqtt')
var client = mqtt.connect({ host: 'localhost', port: 1884 });
client.subscribe('presence');
console.log('Client publishing.. ');
client.publish('presence', 'Client 1 is alive.. Test Ping! ' + Date());
client.end();怎么了?
发布于 2015-12-15 21:32:05
这一页解释得很好:https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets
查看您的代码,您需要允许mosca服务器处理Websockets。以下是您应该更改的服务器设置。
更新到server.js:
var settings = {
port: 1884,
http: {
port: 3000,
bundle: true,
static: './'
}
};更新到index.html:
var client = mqtt.connect({ host: 'ws://localhost', port: 3000 }); https://stackoverflow.com/questions/30873289
复制相似问题