我正在尝试使用HiveMQ通过简单身份验证将客户端连接到服务器。在HiveMQ客户端上,我创建了一个客户端,并使用connectWith()
指定我要使用简单身份验证进行连接。输入用户名和密码后,我得到一个MqttClientStateException
,我在下面留下了它。我是否应该像在本教程中一样输入username
和password
来在服务器上手动存储/配置用户名和密码:
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 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/)进行简单的身份验证。