将paho.mqtt.python连接到mosquitto代理时出现套接字错误

时间:2019-03-04 21:53:13

标签: python python-3.x mqtt mosquitto paho

我正在尝试从python脚本(paho.mqtt.python)连接到mosquitto代理。 我可以使用以下命令从终端连接:

mosquitto_sub -h localhost -p 8883 -v -t 'owntracks/#' -u owntracks -P 12qwaszx

但是当我尝试通过python脚本连接时,出现错误:

Socket error on client <unknown>, disconnecting.

我使用的脚本是示例: (来自此处:https://owntracks.org/booklet/tech/program/

import paho.mqtt.client as mqtt
import json

# The callback for when the client successfully connects to the broker
def on_connect(client, userdata, rc):
    ''' We subscribe on_connect() so that if we lose the connection
        and reconnect, subscriptions will be renewed. '''

    client.subscribe("owntracks/+/+")
    #tried also: client.subscribe("owntracks/#")
# The callback for when a PUBLISH message is received from the broker
def on_message(client, userdata, msg):

    topic = msg.topic

    try:
        data = json.loads(str(msg.payload))

        print "TID = {0} is currently at {1}, {2}".format(data['tid'], data['lat'], data['lon'])
    except:
        print "Cannot decode data on topic {0}".format(topic)

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

client.connect("localhost", 8883, 60)

# Blocking call which processes all network traffic and dispatches
# callbacks (see on_*() above). It also handles reconnecting.

client.loop_forever()

这是我的配置文件的内容(我从我的真实IP更改了“ localhost”,并尝试了两者):

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 8883 "localhost"
persistence true
persistence_location /var/lib/mosquitto/
persistence_file mosquitto.db
log_dest syslog
log_dest stdout
log_dest topic
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
allow_anonymous false
password_file /etc/mosquitto/pwfile

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您的python脚本正在尝试连接到看起来像TLS安全设置的连接,而没有准备将这些详细信息应用于事务的客户端连接方法。请尝试以下操作:

def ssl_prep():
        ssl_context = ssl.create_default_context()
        ssl_context.load_verify_locations(cafile=ca)
        ssl_context.load_cert_chain(certfile=mycert, keyfile=priv)
        return  ssl_context

ca = "PATH_TO_YOUR_CA_FILE"
priv = "PATH_TO_YOUR_PEM_FILE"
mycert = "PATH_TO_YOUR_CERT_FILE"
topics = "YOUR_TOPICS"
broker = "BROKER_URL"
client = mqtt.Client()
ssl_context= ssl_prep()

client.tls_set_context(context=ssl_context)
client.username_pw_set(username="UNAME",password="PASS")
client.connect(broker, port=8883)

在尝试进行连接之前,通过向连接尝试提供ssl上下文,这应该在假设您已经拥有适合自己的设置的所有详细信息的情况下进行连接。

答案 1 :(得分:0)

尝试将KeepAlive时间从1分钟减少到30秒或更短:

client.connect("localhost", 8883, 30)
//Default: connect(host, port=1883, keepalive=60, bind_address=””)