【发布时间】:2023-04-09 21:29:01
【问题描述】:
这是我的代码
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker
print("Connected with result code {0}".format(str(rc))) # Print result of connection attempt
def on_message(client, userdata, message): # The callback for when a PUBLISH message is received from the server.
print("message received " ,str(message.payload.decode("utf-8")))
print("message topic=",message.topic)
print("message qos=",message.qos)
print("message retain flag=",message.retain)
#creating client instance
client = mqtt.Client(client_id="random_id_name")
print("client created ......")
client.on_connect = on_connect # Define callback function for successful connection
client.on_message = on_message # Define callback function for receipt of a message
#connecting to broker/server
hostname = "hostname_I_am_trying_to_connect" #give the host/server/broker name
portnumber = **random_port_number_as_integer_value** #give the port number
client.username_pw_set("username", "password") #give the username and password for the broker/server/host
client.connect(host= hostname ,port= portnumber)
print("client connected to- ",hostname," on port_number:",portnumber)
client.subscribe("login")
print("subscribed to the topic")
client.publish("login","some_message")
print("message published")
client.loop_forever() # Start networking daemon
在这里,我希望收到来自代理的 some_message/unique_id,即 1234/1234_qyehfj_1234_jfjfj。
相反,我收到了一些随机数。看截图:
这里有什么问题?是我的代码有问题还是我向其发送消息的代理有问题?
如果代码有问题,请告诉我如何解决。
【问题讨论】:
-
什么是发布消息?你确定它们是 UTF-8 编码的吗?如果您使用不同的客户端,例如,您会得到什么? mosquitto_sub?
-
如果我没有使用 'utf-8',代理会发送类似“b'1234”的内容。在我使用“utf-8”后,它显示“1234”。我没有使用其他客户端。我应该吗?
-
您需要与发布消息的人交谈并确认他们使用的编码。是的,你应该尝试不同的客户,这就是我问的原因。