我正在 Java 中使用 MqttAsyncClient。以下代码只是我使用它的一部分,当我尝试订阅任何主题时出现错误时,问题就出现了:
客户端未连接 (32104)
private int connections;
private String topic;
private MqttAsyncClient client;
private MqttConnectOptions connOpts;
private MemoryPersistence persistence;
private void configureMqtt()
{
try
{
logger.info("Starting the Mqtt Configuration...");
client = new MqttAsyncClient(conf.getServerURI(), conf.getClientID(), persistence);
connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setUserName(conf.getUserName());
connOpts.setPassword(conf.getPassword().toCharArray());
connOpts.setAutomaticReconnect(true);
logger.info("The Mqtt protocol has been configured successfully!!!");
}
catch (Exception e)
{
logger.error("An error has happened during Mqtt configuration");
logger.error(e);
}
}
public void startSub()
{
try
{
logger.info("Conecting to: " + conf.getServerURI() + " Mqtt Server");
client.connect(connOpts);
logger.info("Connected to the: "+ conf.getServerURI() + " Mqtt Server");
client.setCallback(getCallback());
logger.info("Subscribe to the Topic: " + this.topic);
//Thread.sleep(1000);
client.subscribe(this.topic,1);
logger.info("Successful subscription to topic: " + this.topic);
}
catch(Exception me)
{
logger.error("An error has happened: " + me.toString());
logger.error("\nmsg " + me.getMessage() +
"\nloc " + me.getLocalizedMessage() +
"\ncause " + me.getCause() +
"\nexcep " + me);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
[INFO ] 2019-10-12 21:56:37.234 [main] SpManager - Starting the Mqtt Configuration...
[INFO ] 2019-10-12 21:56:37.388 [main] SpManager - The Mqtt protocol has been configured successfully!!!
[INFO ] 2019-10-12 21:56:37.388 [main] SpManager - Conecting to: tcp://0.tcp.ngrok.io:xxxxx Mqtt Server
[INFO ] 2019-10-12 21:56:37.406 [main] SpManager - Connected to the: tcp://0.tcp.ngrok.io:xxxxx Mqtt Server
[INFO ] 2019-10-12 21:56:37.406 [main] SpManager - Subscribe to the Topic: home/Monitoreo/#
[ERROR] 2019-10-12 21:56:37.427 [main] SpManager - An error has happened: Client is not connected (32104)
[ERROR] 2019-10-12 21:56:37.428 [main] SpManager -
msg Client is not connected
loc Client is not connected
Run Code Online (Sandbox Code Playgroud)
最后我想提一下,当我使用MqttClient而不是MqttAsyncClient时,此代码可以完美运行
问题是您在订阅之前没有等待连接完成。这是因为MqttClient会阻塞,因为MqttAsyncClient返回一个可用于检查操作何时完成的令牌。
快速解决方法是waitForCompletion()在connect()
try
{
logger.info("Connecting to: " + conf.getServerURI() + " Mqtt Server");
IMqttToken token = client.connect(connOpts);
token.waitForCompletion();
logger.info("Connected to the: "+ conf.getServerURI() + " Mqtt Server");
client.setCallback(getCallback());
logger.info("Subscribe to the Topic: " + this.topic);
//Thread.sleep(1000);
client.subscribe(this.topic, 1);
logger.info("Successful subscription to topic: " + this.topic);
}
catch(MqttException me)
{
}
Run Code Online (Sandbox Code Playgroud)