gpt4 book ai didi

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

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

我创建了一个每 3 秒发布消息的 python 应用程序。该消息被发送到 MQTT mosquitto 代理。另一方面,我有一个订阅消息主题的 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应用程序的数据

最佳答案

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

rtu / delete 

在java中

/ rtu / delete

只是一个上升字符“/”

关于java - 我无法使用 MQTT 将 java 应用程序与 python 应用程序连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56393767/

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