我正在使用HiveMQ Java客户端连接到HiveMQ代理。阻止客户端订户不使用任何消息。使用MQTTBox,发布和订阅可以正常工作。这是代码。我正在关注HiveMQ Java Client Documentation
if some_boolean { 1 } else { 0 }
Maven依赖项:
public class MQTTMain {
public static void main(String[] args) {
Mqtt3BlockingClient pubClient = MqttClient.builder()
.useMqttVersion3()
.identifier("pub")
.serverHost("hostaddress")
.serverPort(1883)
.buildBlocking();
Mqtt3BlockingClient subClient = MqttClient.builder()
.useMqttVersion3()
.identifier("sub")
.serverHost("hostaddress")
.serverPort(1883)
.buildBlocking();
pubClient.connectWith().keepAlive(10000).send();
publish(pubClient, "test/topic", "test");
subClient.connectWith().keepAlive(10000).send();
subscribe(subClient, "test/topic");
while (true) {
}
}
public static void subscribe(Mqtt3BlockingClient client, String topic) {
try (final Mqtt3Publishes publishes =
client.publishes(MqttGlobalPublishFilter.ALL)) {
try {
publishes.receive(1, TimeUnit.SECONDS)
.ifPresent(System.out::println);
publishes.receive(10000, TimeUnit.MILLISECONDS)
.ifPresent(System.out::println);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
}
client
.subscribeWith()
.topicFilter(topic)
.qos(MqttQos.AT_LEAST_ONCE)
.send();
}
public static void publish(Mqtt3BlockingClient client, String topic,
String payload) {
client
`enter code here`.publishWith()
.topic(topic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(payload.getBytes())
.send();
}
}
我想念什么吗?任何指针都将真正有帮助。
答案 0 :(得分:7)
您必须先订阅,然后才能接收消息。
Publishes.receive是一项阻止操作,因此它等待直到收到消息为止。 您正在执行接收操作。 您应该执行以下操作:
Mqtt3BlockingClient client = Mqtt3Client.builder()
.identifier("sub")
.serverHost("hostaddress")
.serverPort(1883)
.buildBlocking();
client.connect();
try (final Mqtt3BlockingClient.Mqtt3Publishes publishes =
client.publishes(MqttGlobalPublishFilter.ALL)) {
client.subscribeWith().topicFilter("test/topic").qos(MqttQos.AT_LEAST_ONCE).send();
publishes.receive(1, TimeUnit.SECONDS).ifPresent(System.out::println);
}