我无法使用MQTT将Java应用程序与python应用程序连接

时间:2019-05-31 10:54:51

标签: java python mqtt paho

我创建了一个Python应用程序,每3秒发布一次消息。该消息发送到MQTT蚊子代理。另一方面,我有一个已订阅消息主题的Java应用程序。 当我启动两个应用程序时,Java应用程序什么也收不到。

代码中显示的mqtt代理不正确,出于保密目的,我对其进行了修改。

但是,当我使用mosquitto发布消息时,Java应用程序会收到一条消息。

import paho.mqtt.client as mqtt
import time
import logging

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)

broker='100.100.100.100'
port=1883

def on_log(client, userdata, level, buf):
    logger.info(buf)

def on_connect(client, userdata, flags, rc):
    if rc==0:
        client.connected_flag=True # set flag
        logger.info("Conexion establecida")
    else:
        logger.info("Conexion no establecida code = "+ str(rc))
        client.loop_stop()

def on_disconnect(client, userdata, rc):
    logger.info("Se desconecta el publicador \n")

def on_publish(client, userdata, mid):
    logger.info("Se publica un dato, mid "+ str(mid))

mqtt.Client.connected_flag=False #Crea un flag en la clase

client = mqtt.Client("jmacias_pub")     #Se crea una nueva instancia
client.on_log = on_log
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish

client.connect(host=broker, port=port)
client.loop_start()

while not client.connected_flag: #wait in loop
    logger.info("In wait loop")
    time.sleep(1)

while True:
    time.sleep(3)
    logger.info('Publicando')
    ret = client.publish('rtu/delete','0|[192.168.1.1-866e]', 0)
    ret = client.publish('rtu/delete','0|[192.168.1.2-866e]', 1)
    ret = client.publish('rtu/delete','0|[192.168.1.3-866e]', 2)

client.loop_stop()
client.disconnect()
package com.speedforge.mqtt;

import java.util.concurrent.TimeUnit;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


/**
 * A sample application that demonstrates how to use the Paho MQTT v3.1 Client blocking API.
 */
public class Subscriber implements MqttCallback {
    //Subscribe topics
    static final String TOPIC_ALL="/rtu/delete";
    //Publish topics
    static final String TOPIC_DELETE="/rtu/delete";
    static final String TOPIC_INFO="/rtu/info";
    static final String TOPIC_DESPLOY="/rtu/desploy";


    private final int qos = 2;
    private static MqttClient client;
    //private static MqttClient replay_client;

    public Subscriber(String broker) throws MqttException {
        String host = String.format(broker);
        String clientId = "MQTT-Java-Example";

        MqttConnectOptions conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(true);

        Subscriber.client = new MqttClient(host, clientId, new MemoryPersistence());
        Subscriber.client.setCallback(this);
        Subscriber.client.connect(conOpt);
        Subscriber.client.subscribe(Subscriber.TOPIC_ALL, qos);
    }

    /*
    public void sendMessage(String payload) throws MqttException {
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(qos);
        this.client.publish(this.topic, message); // Blocking publish
    }
    */

    /**
     * @see MqttCallback#connectionLost(Throwable)
     */
    public void connectionLost(Throwable cause) {
        System.out.println("Connection lost because: " + cause);
        System.exit(1);
    }

    /**
     * @see MqttCallback#deliveryComplete(IMqttDeliveryToken)
     */
    public void deliveryComplete(IMqttDeliveryToken token) {

    }

    /**
     * @see MqttCallback#messageArrived(String, MqttMessage)
     */
    public void messageArrived(String topic, MqttMessage message) throws MqttException {
        System.out.println("Se recibe un nuevo mensaje del topic: "+ topic);
        String msg = new String(message.getPayload());
        System.out.println("Payload: " + msg);
    }

    public static void main(String[] args) throws MqttException {
        String broker       = "tcp://100.100.100.100:1883";
        System.out.println("Comienza la subscripcion");
        Subscriber s = new Subscriber(broker);

        try {
            TimeUnit.SECONDS.sleep(60);
            //Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Se obtiene una excepcion del temporizador "+e);
        }

        Subscriber.client.disconnect();
        Subscriber.client.close();
        System.out.println("Finaliza");
    }
}

我必须获取python应用程序发送给java应用程序的数据

1 个答案:

答案 0 :(得分:0)

已解决,在python中使用的主题是

rtu / delete 

和Java

/ rtu / delete

只是一个字母字符'/'