我只是在玩mqtt&&莫斯卡
我已按照以下步骤操作:
npm install -g browserify // install browserify
cd node_modules/mqtt
npm install . // install dev dependencies
browserify mqtt.js -s mqtt > browserMqtt.js
<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>
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,我没有看到任何消息 在我运行服务器的控制台窗口中。
有了这个(它完全相同),我可以看到消息
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();
出了什么问题?
答案 0 :(得分:0)
此页面解释得很好: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 });