MQTT Client not receiving messages
<p>I'm using the following code from MQTT Paho project to subscribe to messages from my mqtt broker. I tested the connection using <code>mosquitto_sub</code> and I receive the messages there. However, when I run the following code it doesn't receive any messages and no output is printed. I checked the topic and host.</p>

<pre><code>import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("test")

# The callback for when a PUBLISH message is received from the server.
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("localhost", 1883, 60)
client.loop_forever()
</code></pre>

<p>The following error is logged by the broker:</p>

<pre><code>Invalid protocol "MQTT" in CONNECT from ::1.
Socket read error on client (null), disconnecting.
</code></pre>

<p><strong>EDIT</strong> Thanks to @hardillb for pointing out the outdated MQTT version.</p>

<p>Everything worked after I did the following:</p>

<ol>
<li>sudo apt-get purge mosquitto</li>
<li>sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa</li>
<li>sudo apt-get update</li>
<li>sudo apt-get install mosquitto</li>
</ol>

<p>This is most likely because you are using an old version of mosquitto and the python is expecting a newer build that supports MQTT 3.1.1</p>

<p>Try changing the code as shown:</p>

<pre><code>import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("test")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

# Change made HERE 
client = mqtt.Client(protocol=MQTTv31)

client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.loop_forever()
</code></pre>

<p>You should also upgrade your broker as soon as possible, that version is incredibly out of date and has a number of known issues, the current version is 1.4.10</p>

python publish-subscribe mqtt