pythonweb使用mqtt,在python中通过websocket进行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()

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.

解决方案

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

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

You can use the websockets as transport by connecting with

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

UPDATE:

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.

Simply create a configuration file for example in

/etc/mosquitto/mosquitto.conf

with the following contents:

listener 1883

protocol mqtt

listener 9001

protocol websockets

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.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值