我无法连接到mqtt中的代理,我想知道为什么?

2024-05-23 17:15:09 发布

您现在位置:Python中文网/ 问答频道 /正文

有三个文件:broker.py;sub.py;pub.py

broker.py:

import logging
import asyncio
from hbmqtt.broker import Broker

logger = logging.getLogger(__name__)

config = {
    'listeners': {
        'default':{
            'type': 'tcp',
            'bind': 'localhost:9999' 
        }
    },
    'sys_interval': 10,
    'topic-check':{
        'enabled': False
    }
}

broker = Broker(config)

@asyncio.coroutine
def startBroker():
yield from broker.start()

if __name__ == '__main__':
formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.get_event_loop().run_until_complete(startBroker())
asyncio.get_event_loop().run_forever()

sub.py:

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('localhost', 9999)

def on_connect(client, userdata, flags, rc):
    print("Connected to a broker!")
    client.subscribe("LINTANGtopic/test")

def on_message(client, userdata, message):
    print(message.payload.decode())

while True:
    client.on_connect = on_connect
    client.on_message = on_message
    client.loop_forever

pub.py:

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('localhost', 9999)

while True:
    client.publish("LINTANGtopic/test", input('Message: '))

所以我首先打开了三个终端: 在第一个终端中,我输入了“pybroker.py”,它运行良好; 在第二个终端中,我输入了“py sub.py”,它不工作,在第二个终端中没有显示任何内容,应该显示“连接到代理”,尽管它使第一个终端显示:

[2020-07-29 14:01:41,925] :: INFO :: hbmqtt.broker :: Listener 'default': 1 connections acquired        
[2020-07-29 14:01:41,926] :: INFO :: hbmqtt.broker :: Connection from ::1:50450 on listener 'default'   
[2020-07-29 14:01:41,937] :: INFO :: transitions.core :: Exited state new
[2020-07-29 14:01:41,937] :: INFO :: transitions.core :: Entered state connected

在第三个终端,我输入了“py pub.py”,它显示如下:

D:\MQTT>py pub.py
Message: 

我需要使订户连接到一个经纪人,我想知道为什么会发生这种情况


Tags: frompyimportinfoclientasyncio终端message
1条回答
网友
1楼 · 发布于 2024-05-23 17:15:09

sub.py无法按您的方式工作

首先client.loop_forever是一个函数,因此需要使用()调用

其次,while True:循环是冗余的,您不应该重复设置回调

请尝试以下操作:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected to a broker!")
    client.subscribe("LINTANGtopic/test")

def on_message(client, userdata, message):
    print(message.payload.decode())

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('localhost', 9999)
client.loop_forever()

相关问题 更多 >