我尝试使用按钮点击事件发布消息。客户端假设发送ON
和OFF
有效负载。由于某种原因,我无法理解为什么这不起作用。
server.js
var io = require('socket.io').listen(5000);
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost:1883')
io.sockets.on('connection', function (socket) {
socket.on('publish', function (data) {
client.publish(data.topic, data.payload);
console.log('Publish to '+ data.payload);
});
});
client.js
var socket = io.connect('http://localhost:5000');
$('#button').ready(function () {
socket.on('connect', function () {
socket.on('mqtt', function (msg) {
console.log(msg.topic + ' ' + msg.payload);
$("#on").click('click', function () {
socket.emit('publish', {topic: 'test/test', payload: 'ON'});
console.log("on");
});
$("#off").click('click', function () {
socket.emit('publish', {topic: 'test/test', payload: 'OFF'});
console.log("off");
})
});
})
})
的index.html
<h1>Test MQTT</h1>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<div id="on" >
<input type="submit" value="ON" >
</div>
<div id="off">
<input type="submit" value="OFF">
</div>
<script src="client.js"></script>
答案 0 :(得分:0)
目前,事件侦听器.click
实际上不会触发,直到socket.on('mqtt'
的回调触发。这将是对'mqtt'
套接字事件的响应。在服务器发布之前,此事件不会触发,但服务器仅在客户端发出时发布 - 这仅在您单击按钮时发生。事件侦听器无法添加,直到它们应该引发触发事件。
重新排列你的逻辑:
$('#button').ready(function () {
socket.on('connect', function () {
$("#on").click('click', function () {
socket.emit('publish', {topic: 'test/test', payload: 'ON'});
console.log("on");
});
$("#off").click('click', function () {
socket.emit('publish', {topic: 'test/test', payload: 'OFF'});
console.log("off");
});
socket.on('mqtt', function (msg) {
console.log(msg.topic, msg.payload);
});
});
});