01 安装
Mosquitto的下载地址:
https://mosquitto.org/files/binary/win64/mosquitto-1.6.11-install-windows-x64.exe
文件下载后,双击后开始安装。
02 配置
进入Mosquitto的安装目录,打开 mosquitto.conf 文件。
- 找到 Default listener 配置块(第200行),开放port和protocol两个配置项
- 找到 Extra listeners 配置块(第358行),添加“listener 9001”、“protocol websockets”两个配置(去掉前面的#号),然后保存。
03 启动
打开CMD命令窗口,切换到Mosquitto安装目录,输入命令“.\mosquitto.exe -c .\mosquitto.conf”并回车,即可启动。
04 连接测试
这里我使用paho-mqtt.js来进行测试,其对应的下载地址是:
https://raw.githubusercontent.com/eclipse/paho.mqtt.javascript/master/src/paho-mqtt.js
下面是具体的测试代码(复制后直接存为.html文件使用),参考https://github.com/eclipse/paho.mqtt.javascript,这里我稍微做了点改动。
<!DOCTYPE HTML>
<html>
<body>
<input id="input" type="text" value="Hello Mosquito!">
<button id="btnSend">向World发布消息</button>
<script src="../../RESEARCH/mqtt/paho-mqtt.js"></script>
<script>
// Create a client instance
var client = new Paho.Client('127.0.0.1', 9001, "mqtt-over-websockets-client-id");
// called when the client loses its connection
client.onConnectionLost = function(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
};
// called when a message arrives
client.onMessageArrived = function(message) {
console.log("onMessageArrived:" + message.payloadString);
};
// connect the client
client.connect({
//called when the client connects
onSuccess: function() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("World");
var message = new Paho.Message("Hello");
message.destinationName = "World";
client.send(message);
document.getElementById('btnSend').addEventListener('click', function() {
var text = document.getElementById('input').value;
message = new Paho.Message(text);
message.destinationName = "World";
client.send(message);
console.log('向' + message.destinationName + '发送消息:' + text);
});
}
});
</script>
</body>
</html>
用谷歌浏览器打开html文件后,分别在【控制台】和【网络】看到以下信息即代表连接成功。
05 订阅、发布测试
上述的Web客户端连接成功后,订阅了一个名为“World”的主题,这里我开启了另一个MQTT的客户端,同时也订阅“World”主题,并向“World”主题发布一条消息“长江长江,我是黄河”,如果Web客户端能收到此消息,则说明“MQTT Client -> MQTT Broker -> Websocket Client”是通畅的。
同时,在Web客户端同样向“World”主题发送一条消息“”,如果MQTT客户端能收到该消息,则说明“Websocket Client -> MQTT Broker -> MQTT Client”是通畅的。
06 总结
Mosquitto1.4.2以后的版本才支持Websocket模式。
所有操作均在WIN10中完成。
本文暂时没有评论,来添加一个吧(●'◡'●)