zoukankan      html  css  js  c++  java
  • Python MQTT 最简单例程搭建

    • MQTT 不是普通的 client server 模型,他还加了一个 代理者。

        根据剑锋的提示,先下载了 paho-mqtt 模块, ubuntu 14.04 上下载方法如下:
        sudo apt-get install  python-pip
        sudo pip install paho-mqtt
        source paho-mqtt/bin/activate
        sudo apt-get install python-virtualenv
        virtualenv paho-mqtt
    
    • 下载 broker 代理

        参考: http://www.steves-internet-guide.com/install-mosquitto-linux/#install-test
        sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
         sudo apt-get update
         sudo apt-get install mosquitto
         sudo apt-get install mosquitto-clients
         sudo server mosquitto start
        mosquitto -v
        // 带调试信息的启动
    
    • server 代码编写

        import paho.mqtt.client as mqtt
    
        def on_connect(client, userdata, flags, rc):
            print("Connected with result code "+str(rc))
            client.subscribe("chat")
    
        def on_message(client, userdata, msg):
            print(msg.topic+" " + ":" + str(msg.payload))
    
        client = mqtt.Client()
        client.on_connect = on_connect
        client.on_message = on_message
        client.connect("127.0.0.1", 1883, 60)
        client.loop_forever()
    
    • client 代码编写

        import paho.mqtt.client as mqtt
    
        HOST = "127.0.0.1"
        PORT = 1883
    
        def test():
            client = mqtt.Client()
            client.connect(HOST, PORT, 60)
            client.publish("chat","hello chenfulin",2)
            client.loop_forever()
    
        if __name__ == '__main__':
            test()
    
    • 启动

        python server.py
        python client.py
    
  • 相关阅读:
    BZOJ 2212/BZOJ 3702
    BZOJ 4761 Cow Navigation
    BZOJ 3209 花神的数论题
    BZOJ 4760 Hoof, Paper, Scissors
    BZOJ 3620 似乎在梦中见过的样子
    BZOJ 3940 Censoring
    BZOJ 3942 Censoring
    BZOJ 3571 画框
    BZOJ 1937 最小生成树
    BZOJ 1058 报表统计
  • 原文地址:https://www.cnblogs.com/chenfulin5/p/8882055.html
Copyright © 2011-2022 走看看