#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Client paho-mqtt MqttServer
# main.py
import paho.mqtt.publish as publish
from json import dumps
from ssl import PROTOCOL_TLSv1
import urllib2
class MqttClient():
host = 'mqtt.xyz.com'
port = '1883'
auth = {}
topic = '%s/streams'
tls = None
def __init__(self, auth, tls=None):
self.auth = auth
self.topic = '%s/streams' % auth['username']
if tls:
self.tls = tls
self.port = '8883'
def publish(self, msg):
try:
publish.single (topic=self.topic,payload=msg,hostname=self.host,
tls=self.tls,port=self.port)
except Exception, ex:
print ex
if __name__ == '__main__':
auth = {'username': 'your username', 'password': ''}
#tls_dict = {'ca_certs': 'ca_certs.crt', 'tls_version': PROTOCOL_TLSv1} # sslvers.
msg_dict={'protocol':'v2','device':'Development Device','at':'now','data':{'temp':21,'hum':58}}
client_mqtt =MqttClient(auth=auth) # non ssl version
#client_mqtt =MqttClient(auth=auth, tls=tls_dict) # ssl version
client_mqtt.publish(dumps(msg_dict))
我猜我的组织的代理设置阻止了请求,因此请引导我在上面的代码中包含代理设置。
例如,如果地址是' proxy.xyz.com'和端口号是' 0000'我的网络用户名是' xyz'和密码是' abc'
答案 0 :(得分:3)
您还没有提到您正在谈论的代理类型,但假设您要使用HTTP代理。
由于两个协议不兼容,您无法使用HTTP代理转发原始MQTT流量。
如果您要连接的代理通过Websockets支持MQTT,那么您应该能够连接现代HTTP代理,但这不适用于您发布的代码。
答案 1 :(得分:2)
您的代码应遵循以下规定
import socks
import socket
import paho.mqtt.client as mqtt
client = mqtt.Client(client_id='the-client-id')
client.username_pw_set('username', 'password')
# set proxy ONLY after client build but after connect
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_HTTP, addr="proxy.xyz.com", port=0000, rdns=True,username="xyz", password="abc")
socket.socket = socks.socksocket
# connect
client.connect('mqtt.host', port=1883, keepalive=60, bind_address="")
client.loop_forever()
答案 2 :(得分:0)
我在使用socks
代理服务器和PySocks的情况下解决了此问题
import socks
import socket
import paho.mqtt.client as mqtt
client = mqtt.Client(client_id='the-client-id')
client.username_pw_set('username', 'password')
# set proxy ONLY after client build but after connect
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "socks.proxy.host", 1080)
socket.socket = socks.socksocket
# connect
client.connect('mqtt.host', port=1883, keepalive=60, bind_address="")
client.loop_forever()
答案 3 :(得分:0)
Paho社区在2018年添加了此功能。 https://github.com/eclipse/paho.mqtt.python/pull/315
由于没有人添加代码段,因此我正在添加代码段。只需为客户端对象设置代理选项。
client = mqtt.Client()
client.proxy_set(proxy_type=socks.HTTP, proxy_addr=proxy_host, proxy_port=proxy_port)