在python中的Websocket上的MQTT [英] MQTT over websocket in python

查看:1113
本文介绍了在python中的Websocket上的MQTT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中是否有任何支持以8080端口订阅mqtt代理

is there any support in python to subscribe on mqtt broker with port 8080

 import sys
 import paho.mqtt.client as mqtt

 def on_connect(mqttc, obj, flags, rc):
     print("rc: "+str(rc))

 def on_message(mqttc, obj, msg):
     print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

 def on_publish(mqttc, obj, mid):
     print("mid: "+str(mid))

 def on_subscribe(mqttc, obj, mid, granted_qos):
     print("Subscribed: "+str(mid)+" "+str(granted_qos))

 def on_log(mqttc, obj, level, string):
     print(string)

 mqttc = mqtt.Client()   
 mqttc.on_message = on_message
 mqttc.on_connect = on_connect
 mqttc.on_publish = on_publish
 mqttc.on_subscribe = on_subscribe
 mqttc.connect("test.mosquitto.org", 8080, 60)
 mqttc.subscribe("test/iot", 0)

 mqttc.loop_forever()

我无法使用此代码连接. Mosquitto在端口8080上具有websocket支持,但是此paho库对此不起作用. python的任何解决方案? 我在Windows 10上使用python 2.7.

i can not connect with this code. Mosquitto has websocket support at port 8080 but this paho library does not work for it. any solution for python? i am using python 2.7 on windows 10.

推荐答案

几天前,Paho MQTT模块引入了websocket支持.我认为它尚未发布,但是您可以使用Linux在Linux分支下的主服务器上安装

The Paho MQTT module introduced websocket support some days ago. I don't think it is released yet, but you can install from the master under Linux branch using

pip install git+git://github.com/eclipse/paho.mqtt.python.git

也可以在Windows下使用. (感谢评论中的信息)

Also works under windows. (Thanks for info from the comments)

您可以通过与

mqttc = mqtt.Client(transport="websockets")

更新:

如果由于还需要连接浏览器客户端(例如MQTT.js)而尝试将Websocket协议与python客户端一起使用,则还可以将mosquitto配置为侦听 websockets 和正常的 mqtt协议.

If you try to use the websocket protocol with the python client because you also need to connect a browser client (for example MQTT.js) then you can also configure mosquitto to listen to websockets and the normal mqtt protocol.

只需在

/etc/mosquitto/mosquitto.conf

具有以下内容:

listener 1883
protocol mqtt

listener 9001
protocol websockets

然后,您可以使用以下命令运行mosquitto

Then you can then run mosquitto with

mosquitto -c /etc/mosquitto/mosquitto.conf

您应该会看到类似的输出:

You should see similar output:

1469015320: mosquitto version 1.4.8 (build date 2016-05-3112:07:40+0200) starting
1469015320: Config loaded from /etc/mosquitto/mosquitto1.conf.
1469015320: Opening ipv4 listen socket on port 1883.
1469015320: Opening ipv6 listen socket on port 1883.
1469015320: Opening websockets listen socket on port 9001.

您的python客户端随后连接到端口1883,浏览器客户端连接到9001

Your python client then connects to port 1883 and the browser client to 9001

您可以使用 what-mqtt浏览器客户端来测试websocket侦听器.只需将其指向ws://localhost:9001

You can use what-mqtt browser client to test the websocket listener. Just point it to ws://localhost:9001

这篇关于在python中的Websocket上的MQTT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆