python3对emqtt的简单操作

发布时间:2020-07-28 20:00:07 作者:白话
来源:网络 阅读:995

需要先下载外部包

pip install paho-mqtt
发布者
import paho.mqtt.client as mqtt

HOST = "192.168.44.31"
PORT = 1883

def Publish_Message():
    client = mqtt.Client()
    client.username_pw_set(username='admin', password='public')  # 用于添加了插件认证方式后
    client.connect(HOST, PORT, 60)
    for x in range(10):
        Message = "hello" + str(x)
        client.publish("services", Message, 0)  # 发布一个主题为'services',内容为‘hello x’的信息
    # time.sleep(10)
    client.loop_forever()  # 保持连接状态

if __name__ == '__main__':
    Publish_Message()

发布者,主要内容:publish("topic_name","utf8_message",Qos)


订阅者
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))  # rc表示返回来的状态值
    client.subscribe("services")

def on_message(client, userdata, msg):
    print(msg.topic+" " + ":" + str(msg.payload))

if __name__ == "__main__":
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set(username='admin', password='public')  # 用于添加了插件认证方式后
    client.connect("192.168.44.31", 1883, 60)
    client.loop_forever()

订阅者,信息的产出在msg.payload

rc值代表的含义:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.

推荐阅读:
  1. tomcat简单操作
  2. Python3 数据库增删改查简单操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python3 emqtt

上一篇:测试的第三重境界:挑战零缺陷

下一篇:Boost asio 同步连接超时设置失败

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》