Search code examples
pythonwindowsmqttmosquittopaho

ConnectionRefusedError when connecting to test.mosquitto.org


I'm completely new to this protocol, python and paho-mqtt. I want the simplest way for two publishers to publish to a topic. I also want a subscriber to listen to these messages. Previously, I don't know if it was because of a change I made in Python, but when I run the subscriber and then the first publisher, there is no problem. However, when I run the second one, I get this error:

Traceback (most recent call last):
  File "C:\...\MQTT\DigitalTwin2.py", line 14, in <module>
    dt_client.connect("test.mosquitto.org", 1883, 60)
  File "C:\...\Python\Python39\lib\site-packages\paho\mqtt\client.py", line 914, in connect
    return self.reconnect()
  File "C:\...\Python\Python39\lib\site-packages\paho\mqtt\client.py", line 1044, in reconnect
    sock = self._create_socket_connection()
  File "C:\...\Python\Python39\lib\site-packages\paho\mqtt\client.py", line 3685, in _create_socket_connection
    return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source)
  File "C:\...\Python\Python39\lib\socket.py", line 843, in create_connection
    raise err
  File "C:\...\Python\Python39\lib\socket.py", line 831, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

The Python codes are as follows: (The codes for the publishers are the same, only the client names are different)

Publisher #1&2:

import paho.mqtt.client as mqtt
from random import uniform
import time

def on_dt_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to Digital Twin-1 with result code 0")
    else:
        print("Connection to Digital Twin-1 failed with result code " + str(rc))

dt_client = mqtt.Client("Digital Twin-1")
dt_client.on_connect = on_dt_connect

dt_client.connect("test.mosquitto.org", 1883, 60)

while True:
    randNumber = uniform(3.0, 4.0)
    randNumber = round(randNumber, 4)
    dt_client.publish("topic", "Digital Twin-1: " + str(randNumber))
    print("..." + str(randNumber) + "...")
    time.sleep(1)

Subscriber:

import paho.mqtt.client as mqtt
import time

def on_sd_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to Smart Device with result code 0")
    else:
        print("Connection to Smart Device failed with result code " + str(rc))

def on_sd_message(client, userdata, message):
    print("...", str(message.payload.decode("utf-8")))

device_client = mqtt.Client("Smart Device")
device_client.on_connect = on_sd_connect

device_client.connect("test.mosquitto.org", 1883, 60)

device_client.loop_start()
device_client.subscribe("topic")
device_client.on_message = on_sd_message

time.sleep(30)

device_client.loop_stop()

I've looked through previous questions, but no one seems to be trying to connect three clients. Additionally, the things I did before were:

  • I added a new rule with New Rule from Windows Defender.

  • While using MQTT Explorer, I added a password. When I couldn't connect with the password, I closed MQTT Explorer. I deleted the password file I created from the mosquitto folder.

I tried to follow these steps by watching YouTube videos.


Solution

  • I copied and pasted your publisher and subscriber code exactly with no modifications:

    publisher1.py:

    import paho.mqtt.client as mqtt
    from random import uniform
    import time
    
    def on_dt_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to Digital Twin-1 with result code 0")
        else:
            print("Connection to Digital Twin-1 failed with result code " + str(rc))
    
    dt_client = mqtt.Client("Digital Twin-1")
    dt_client.on_connect = on_dt_connect
    
    dt_client.connect("test.mosquitto.org", 1883, 60)
    
    while True:
        randNumber = uniform(3.0, 4.0)
        randNumber = round(randNumber, 4)
        dt_client.publish("topic", "Digital Twin-1: " + str(randNumber))
        print("..." + str(randNumber) + "...")
        time.sleep(1)
    

    subscriber.py:

    import paho.mqtt.client as mqtt
    import time
    
    def on_sd_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to Smart Device with result code 0")
        else:
            print("Connection to Smart Device failed with result code " + str(rc))
    
    def on_sd_message(client, userdata, message):
        print("...", str(message.payload.decode("utf-8")))
    
    device_client = mqtt.Client("Smart Device")
    device_client.on_connect = on_sd_connect
    
    device_client.connect("test.mosquitto.org", 1883, 60)
    
    device_client.loop_start()
    device_client.subscribe("topic")
    device_client.on_message = on_sd_message
    
    time.sleep(30)
    
    device_client.loop_stop()
    

    I can run both of them on my local machine with no problems.

    If I copy the publisher code and change the client ID (e.g. change Digital Twin-1 to be Digital Twin-2) then I can run 2 publishers concurrently and 1 subscriber. Again, everything works fine.

    Therefore, your code is not the problem.

    I believe it's something in your environment preventing network access to test.mosquitto.org:1883 or possibly a problem with test.moquitto.org itself. For what it's worth, the website for test.mosquitto.org lists these caveats (emphasis mine):

    This server is provided as a service for the community to do testing, but it is also extremely useful for testing the server. This means that it will often be running unreleased or experimental code and may not be as stable as you might hope. It may also be slow - the broker often runs under valgrind or perf. Finally, not all of the features may be available all of the time, depending on what testing is being done. In particular, websockets and TLS support are the most likely to be unavailable.

    In general you can expect the server to be up and to be stable though.