• 树莓派搭建自己的MQTT服务器


    MQTT协议是广泛应用的物联网协议,使用测试MQTT协议需要MQTT的代理。有两种方法使用MQTT服务,
    一是租用现成的MQTT服务器,如阿里云,百度云,华为云等公用的云平台提供的MQTT服务,
    使用公用的MQTT服务器的好处是省事,但如果仅仅用于测试学习还需要注册帐号,灵活性差些,
    有的平台还需要付费。另一方法是自己使用开源的MQTT组件来搭建。
    MQTT服务器非常多,如apache的ActiveMQ,emtqqd,HiveMQ,Emitter,Mosquitto,Moquette等等。
    这里介绍的是用轻量级的mosquitto开源项目来搭建一个属于自己的MQTT服务器。
     
    下载mosquitto需要的依赖
    sudo apt-get install libssl-dev
    sudo apt-get install uuid-dev
    sudo apt-get install cmake
     
    下载mosquitto并解压
    wget http://mosquitto.org/files/source/mosquitto-1.6.9.tar.gz
    tar -zxvf mosquitto-1.6.9.tar.gz
      
     
    进入目录
    cd mosquitto-1.6.9
      
    编译
    make
     
    安装
    sudo make install
     
    #启动mosquitto
    mosquitto -v
    1535473957: mosquitto version 1.5.4 starting
    1535473957: Using default config.
    1535473957: Opening ipv4 listen socket on port 1883.
    1535473957: Opening ipv6 listen socket on port 1883.
    这时候mosquitto就会以默认的参数启动。如果需要带配置文件可以修改配置文件mosquitto.conf
    可以看到,mosquitto监听的端口为1883.
    这时候我们的MQTT服务器就搭建好了。
    可找一个mqtt客户端来测试一下。
     
    测试过程:
    Android app 发布topic: 
    链接:https://pan.baidu.com/s/1ABG8GZHPjnoWe-lfCh8kUg  密码:vn6w
     
    pc端 接收topic 消息:
    import time
    import paho.mqtt.client as mqtt
    # The callback for when the client receives a CONNACK response from the server.
    
    HOST = "192.168.199.111"
    PORT = 1883
    
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("连接成功")
            print("Connected with result code " + str(rc))
    
    def on_message(client, userdata, msg):
        print(msg.topic + " " + str(msg.payload))
    client = mqtt.Client(protocol=3)
    client.username_pw_set("admin", "password")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(host=HOST, port = PORT, keepalive=60)  # 订阅频道
    time.sleep(1)
    client.subscribe("test")
    #client.subscribe([("public", 0), ("test", 2)])
    client.loop_forever()
     
     
     
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    事务隔离级别
    OpenSessionInView
    图像平滑处理(滤波)
    [原]Nginx+Lua服务端合并静态文件
    检查数据倾斜分布
    SQL Server研究之统计信息—发现过期统计信息并处理具体解释
    GDALWarp设置GDALWarpOptions::dfWarpMemoryLimit过大时处理失败
    Android Studio 2.0 稳定版新特性介绍
    供应商和管理员查看供应商地址簿信息SQL
    Table AdvanceTable针对表内行禁用multipleSelection , singleSelection
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14182007.html
Copyright © 2020-2023  润新知