gpt4 book ai didi

python - 测试docker容器中的Python mqtt客户端连接到mqtt代理docker容器

转载 作者:行者123 更新时间:2023-12-02 18:26:38 25 4
gpt4 key购买 nike

我有一个包含python脚本单元测试的测试容器,以测试与mqtt代理的连接。 mqtt代理是另一个使用eclipse-mosquitto:latest的docker容器。

我还创建了一个docker网络。

以下是docker语句:

docker network create test_network
docker run -d -p 21883:1883 --name=gatewaymqtt --network=test_network -v "$PWD/work/mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf" -v "$PWD/work/mosquitto/data:/mosquitto/data" -v "$PWD/work/mosquitto/log:/mosquitto/log" eclipse-mosquitto:latest

docker build -t test -f ./Dockerfile-test .
docker run --network=test_network test

在测试容器中,它正在运行此python单元测试:

class TestClient(unittest.TestCase):

def test_mqtt_connect(self):
log = logging.getLogger("test_mqtt_connect")
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
log.debug("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("$SYS/#")

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

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("gatewaymqtt ", 21883, 60)
sleep(5)
client.disconnect()

if __name__ == '__main__':
unittest.main()

但是,我没有看到来自测试容器的任何传入连接?

这是测试容器的日志:
======================================================================
ERROR: test_mqtt_connect (__main__.TestClient)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_socketio.py", line 69, in test_mqtt_connect
client.connect("gatewaymqtt ", 21883, 60)
File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 937, in connect
return self.reconnect()
File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 1071, in reconnect
sock = self._create_socket_connection()
File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
File "/usr/local/lib/python3.7/socket.py", line 728, in create_connection
raise err
File "/usr/local/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

----------------------------------------------------------------------

最佳答案

当您在docker网络内部连接时,请使用实际端口,而不要暴露一个端口。连接到Docker主机和docker网络内部的21883时,应使用1883

...
client.connect("gatewaymqtt ", 1883, 60)
...

关于python - 测试docker容器中的Python mqtt客户端连接到mqtt代理docker容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com