如何使用 flespi 连接和发布 Java Hive MQTTClient?

How to connect and publish Java Hive MQTTClient with flespi?

flespi.io 使用身份验证令牌作为用户名,如果需要,您也可以将令牌设置为密码。如何使用 HiveMQ Java 实现连接到 flespi?

Mqtt3AsyncClient client = MqttClient.builder()
                .useMqttVersion3()
                .identifier(UUID.randomUUID().toString())
                .simpleAuth()
                .username(mqttClientConfig.getUser())
                .password(mqttClientConfig.getPassword().getBytes()).applySimpleAuth()
                .serverHost(mqttClientConfig.getBrokerHost())
                .serverPort(mqttClientConfig.getBrokerPort())
                .buildAsync();
client.connect()
                .whenComplete((connAck, throwable) -> {
                    if (throwable != null) {
                        logger.error("MQTT connection error: ", throwable);
                    } else {
                        client.publishWith()
                                .topic(mqttClientConfig.getPublishTopic())
                                .payload(payload.getBytes())
                                .qos(MqttQos.fromCode(mqttClientConfig.getQos()))
                                .send()
                                .whenComplete((mqtt3Publish, subThrowable) -> {
                                    if (subThrowable != null) {
                                        logger.error("MQTT subscripton error: ", subThrowable);
                                    } else {
                                        logger.info("Published on: {}", mqttClientConfig.getTopic());
                                    }
                                });
                        client.disconnect();
                    }
                });

我收到错误:

INFO  n.k.s.mqtt.HiveMqttClient - Connecting to mqtt.flespi.io:8883... 
ERROR n.k.s.mqtt.HiveMqttClient - MQTT connection error:  
com.hivemq.client.mqtt.exceptions.ConnectionClosedException: Server closed connection without DISCONNECT.

端口 8883 通常用于基于 TLS 的 MQTT

如果是这样,那么您需要向构建器中添加如下内容

.sslWithDefaultConfig()

查看 HiveMQ 教程here