java - 如何在 HiveMQ 中正确连接身份验证?

标签 java mqtt hivemq

我正在尝试使用 HiveMQ 通过简单的身份验证将客户端连接到服务器。在 HiveMQ Client 上,我创建了一个客户端并使用 connectWith() 指定我想通过简单例份验证进行连接。当我输入用户名和密码时,我得到一个 MqttClientStateException,我把它留在下面。我是否应该在服务器上手动存储/配置用户名和密码,因为我刚刚输入了 usernamepassword 就像这里的教程:

https://hivemq.github.io/hivemq-mqtt-client/docs/mqtt_operations/connect.html#authenticationauthorization .

代码:

Mqtt5BlockingClient publisher = Mqtt5Client.builder()
    .identifier(UUID.randomUUID().toString()) // the unique identifier of the MQTT client. The ID is randomly generated between 
    .serverHost("localhost")  // the host name or IP address of the MQTT server. Kept it localhost for testing. localhost is default if not specified.
    .serverPort(1883)  // specifies the port of the server
    .addConnectedListener(context -> ClientConnectionRetreiver.printConnected("Publisher1"))         // prints a string that the client is connected
    .addDisconnectedListener(context -> ClientConnectionRetreiver.printDisconnected("Publisher1"))  // prints a string that the client is disconnected
    .buildBlocking();  // creates the client builder                
    publisher.connectWith() // connects the client
        .simpleAuth()
            .username("Username")
            .password("Password".getBytes())
            .applySimpleAuth();

异常(exception):

Exception in thread "SubThread1" com.hivemq.client.mqtt.exceptions.MqttClientStateException: MQTT client is not connected.
at com.hivemq.client.internal.mqtt.MqttBlockingClient.subscribe(MqttBlockingClient.java:101)
at com.hivemq.client.internal.mqtt.message.subscribe.MqttSubscribeBuilder$Send.send(MqttSubscribeBuilder.java:184)
at com.main.SubThread.run(SubThread.java:83)
at java.base/java.lang.Thread.run(Thread.java:834)

最佳答案

您忘记发送连接消息

publisher.connectWith()
        .simpleAuth()
            .username("Username")
            .password("Password".getBytes())
            .applySimpleAuth()
        .send();

如果你真的想验证客户端,你必须配置服务器。借助 HiveMQ,您可以使用基于文件角色的访问控制扩展 (https://www.hivemq.com/extension/file-rbac-extension/) 进行简单的身份验证。

关于java - 如何在 HiveMQ 中正确连接身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742257/

相关文章:

java - 使用 SmallRye react 消息动态发布/订阅 MQTT

android - 解释 ANR 堆栈跟踪

kotlin - HiveMQ MQTT 客户端 : subscribe to multiple topics

java - 如何在 HiveMQ 客户端中正确使用 SSL 配置? (MQTT)

java - hql查询获取最近1个月的记录

java - JPA + hibernate 环境

java - Spring MQTT : catch ConnectException

java - HiveMQ Client中如何获取客户端连接信息? (MQTT)

java - save 方法无法使用 Hibernate + Spring 保存对象

java将对象保存在CPU寄存器中