美文网首页
python 实现mq消息推送

python 实现mq消息推送

作者: 唐朝早晨 | 来源:发表于2019-07-05 12:54 被阅读0次

    客户端:

    # encoding: utf-8
    import paho.mqtt.client as mqtt
    import sys
    
    ThemControl = "mq主题"
    # print(ThemControl)
    print(ThemControl)
    #要发送的mq消息
    data = "1,1"
    HOST = "mq服务器地址"
    PORT = 端口号
    def test():
        client = mqtt.Client()
        client.connect(HOST, PORT, 60)
        client.publish(ThemControl,data,2)
        # client.loop_forever()
    if __name__ == '__main__':
        test()
    

    服务端:

    #-*- coding: utf-8 -*-
    import paho.mqtt.client as mqtt
    import os
    import time
    import sys
    
    ThemControl = "mq主题"
    def on_connect(client, userdata, flags, rc):
        client.subscribe(ThemControl)
        # print("Connected with result code "+str(rc))
    def on_message(client, userdata, msg):
        print(msg.topic+" " + ":" + str(msg.payload))
    # client.loop_forever()
    def main():
      client = mqtt.Client()
      client.on_connect = on_connect
      client.on_message = on_message
      client.connect("mq服务器地址", 端口号, 60)
      while data:
        client.loop()
    if __name__== '__main__':
      main()
    

    注意:服务端监听的主题和客户端推送的主题必须是同一个主题。

    相关文章

      网友评论

          本文标题:python 实现mq消息推送

          本文链接:https://www.haomeiwen.com/subject/fewshctx.html