【发布时间】:2016-04-24 10:39:30
【问题描述】:
按照MQTT-over-Websockets 的提示,我尝试添加到这个已经工作的设置中。 服务器(代理)
var mosca = require('mosca')
var settings = {
port: 1883,
persistence: mosca.persistence.Memory,
http: {port: 3333, bundle: true, static: './'}
};
var server = new mosca.Server(settings, function() {
console.log('Mosca server is up and running')
});
server.published = function(packet, client, cb) {
if (packet.topic.indexOf('echo') === 0) {
return cb();
}
var newPacket = {
topic: 'echo/' + packet.topic,
payload: packet.payload,
retain: packet.retain,
qos: packet.qos
};
console.log('newPacket', newPacket);
server.publish(newPacket, cb);
}
client2.js
var mqtt = require('mqtt')
client = mqtt.createClient(1883, 'localhost');
client.subscribe('presence');
client.on('message', function(topic, message) {
console.log(message.toString());
});
console.log('Client started...');
client1.js
var mqtt = require('mqtt')
client = mqtt.createClient(1883, 'localhost');
client.subscribe('presence');
console.log('Client publishing.. ');
client.publish('presence', 'Client 10 is alive.. Test Ping! ' + Date());
client.end();
所以我想让一个网络客户端工作,我按照mqtt in browser w webpack 中的说明创建 browserMqtt.js
cd node_modules/mqtt
npm install . // install dev dependencies
webpack mqtt.js ./browserMqtt.js --output-library mqtt
并在网页中使用它来模仿节点 client2.js 已经做的事情。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webmqtt</title>
<script src="./dist/browserMqtt.js"></script>
</head>
<body>
<h1>hello</h1>
<script>
client = mqtt.connect({ host: 'localhost', port: 3333 });
client.subscribe('presence');
client.on('message', function(topic, payload) {
console.log(message.toString())
});
client.publish('presence', 'Web Client is alive.. Test Ping! ' + Date());
</script>
</body>
</html>
它的发布消息没有显示在其他客户端上,也没有得到它订阅的消息。然而,它确实会导致一个新数据包到达服务器,该数据包看起来像浏览器客户端的 ID。
【问题讨论】:
标签: node.js websocket browserify webpack mqtt