mqtt_client.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/3/7 9:43
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: mqtt_client.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. # encoding: utf-8
  15. import paho.mqtt.client as mqtt
  16. def on_connect(client, userdata, flags, rc):
  17. print("Connected with result code "+str(rc))
  18. client.subscribe("chat")
  19. def on_message(client, userdata, msg):
  20. print(msg.topic+" " + ":" + str(msg.payload))
  21. client = mqtt.Client()
  22. client.on_connect = on_connect
  23. client.on_message = on_message
  24. client.connect("192.168.136.45", 1883, 60)
  25. client.loop_forever()
  26. exit()
  27. import paho.mqtt.client as mqtt
  28. HOST = "192.168.136.45"
  29. PORT = 1883
  30. def test():
  31. client = mqtt.Client()
  32. client.username_pw_set(username='我是设备aa',password='xxxxxxx')
  33. client.connect(HOST, PORT, 60)
  34. client.publish("chat", "lalalallalalalalal", 2)
  35. # client.loop()
  36. client.loop_forever()
  37. if __name__ == '__main__':
  38. test()