一.mqtt 服务器的安装,有很多开源和免费的服务器,网上找找,重点是要支持websocket 。 如:Apache ActiveMQ , mosquitto, EMQ 等等。

二. 代码试例

python 发布和订阅 mqtt 消息, 注意下面是用websocket方式,mqtt server 需要开启websocket服务。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Project: mqtt
# File   : mqttClientTest.py
# Author : Long.Xu <fangkailove@yeah.net>
#          http://gnolux.blog.csdn.net
#          QQ:26564303
# Time   : 2020-11-21
# Copyright 2020 Long.Xu All rights Reserved. 

import paho.mqtt.client as mqtt

def on_msg(clnt,udata,msg):
   print(msg.topic+" "+str(msg.payload))

def on_cnt(client, userdata, flags, rc):
   print("connect" + str(rc))

def test():
   topic = "testtopic"
   wsbroker = "xxx.xxx.xxx.xxx" # mqtt websocket  ip
   wsport = 8234 # mqtt websocket port 

   client = mqtt.Client(transport="websockets") #ussed websockets
   client.on_message=on_msg
   client.on_connect=on_cnt
   client.username_pw_set('username','password') #set user and password

   client.connect(wsbroker,wsport)
   client.publish(topic,'test msg from xulong python client') #publish a topic
   client.subscribe(topic)#subsribe a topic 
   client.loop_forever()

if __name__ == '__main__':
   test()
~                           

 

 javascript 发布和订阅mqqt消息 , js 支持的是 websocket, 要求mqtt server 支持并打开了  websocket服务

	<script src="../js/mui.min.js"></script>
	<script src="../js/mqttws31.js"></script>
	<script>
		mui.init({
			swipeBack: true //启用右滑关闭功能
		});

		var topic = "testtopic";
        
		var wsbroker = "xxx.xxx.xxx.xxx"; // mqtt websocket  ip
		var wsport = Number(8234); // mqtt websocket port 
		var client = new Paho.MQTT.Client(wsbroker, wsport,
			"myclientidf_" + parseInt(Math.random() * 100, 10));


		client.onConnectionLost = function(responseObject) {
			console.log("CONNECTION LOST - " + responseObject.errorMessage);
		};
		client.onMessageArrived = function(message) {
			console.log("RECEIVE ON " + message.destinationName + " PAYLOAD " + message.payloadString);

		};
		
		var options = {
			userName: "username", // UserName
			password: "password", // Password
			timeout: 30,
			keepAliveInterval: 30,
			onSuccess: function() {
				console.log("CONNECTION SUCCESS");
				// subscribe a topic
				client.subscribe(topic, {
					qos: 1
				});
				
			},
			onFailure: function(message) {
				console.log("CONNECTION FAILURE - " + message.errorMessage);
			}
		};

		console.log("CONNECT TO " + wsbroker + ":" + wsport);
		client.connect(options);


		function pub() {
			message = new Paho.MQTT.Message(document.getElementById("msg").value);
			message.destinationName = topic;
			client.send(message);
		}
	</script>

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐