title: MQTT: How to send a message without to call loop_forever()
body: <p>I'm using MQTT since a while to monitor some channels I subscribed. Now I want to implement to send a message as reaction to a state. I got it running with the code below, where I just react in the on_message callback (code 1 at the end). But this code uses </p>
  
  <pre><code>loop_forever()
  </code></pre>
  
  <p>in the main code which is blocking. </p>
  
  <p>What I would like to do is to just send a single message to MQTT. When I try the following (with all different loop-functions), nothing is received by the MQTT server:</p>
  
  <pre><code>import paho.mqtt.client as mqtt
  
  if __name__ == "__main__":
  
      mqtt_client = mqtt.Client()
      mqtt_client.connect("192.168.178.204", 1883, 60)
      mqtt_client.username_pw_set(username="test", password="test")
  
      mqtt_client.publish(topic='TEST', payload='CCCCCCCCC', retain=False)
      mqtt_client.loop_write()
      # mqtt_client.loop()
      # mqtt_client.loop_start()    
  
      mqtt_client.disconnect()
  </code></pre>
  
  <p>How can I send a message to MQTT which does not block the process?</p>
  
  <hr>
  
  <p>Code 1:</p>
  
  <pre><code>import paho.mqtt.client as mqtt
  
  def on_connect(client, userdata, rc):
      topic_list = [("TEST_MS", 1)]
      if rc == 0:
          print("Successful connected and subscribed to: {}".format(topic_list))
      client.subscribe(topic_list)
  
  
  def on_message(client, userdata, msg):
      print(msg.payload)
      client.publish(topic='TEST_MS2', payload=msg.payload, retain=False)
  
  
  def on_publish(client, userdata, mid):
      print("message published")
  
  
  def on_subscribe(mosq, obj, mid, granted_qos):
      print("Subscribed: " + str(mid) + " " + str(granted_qos))
  
  if __name__ == "__main__":
  
      mqtt_client = mqtt.Client()
  
      mqtt_client.on_connect = on_connect
      mqtt_client.on_message = on_message
      mqtt_client.on_publish = on_publish
      mqtt_client.on_subscribe = on_subscribe
  
      mqtt_client.connect("192.168.178.204", 1883, 60)
      mqtt_client.username_pw_set(username="test", password="test")
  
      # mqtt_client.publish(topic='TEST_MS', payload='CCCCCCCCC', retain=False)
      mqtt_client.loop_forever()
  
      mqtt_client.disconnect()
  </code></pre>