我看了很多flutter使用MQTT的文章,并使用官方给出的使用步骤,用官方的测试的URL是可以接收和发送数据的.但是使用公司的URL就无法收到消息,控制台一直打印报错.
arduino
mqtt-client::ConnectionException: The connection must be in the Connected state in order to perform this operation
arduino
MqttConnectionKeepAlive::pingRequired - NOT sending ping - not connected
因为客户端与MQTT服务端没有成功建立连接,导致后续操作就一直报错, 我用这些报错信息,搜索了一圈下来,完全找不到解决答案,我使用的MQTT插件是:mqtt_client: ^10.0.0
,我下载了一个MQTT的客户端软件安装到Mac上方便调试.MQTTX
在这个工具中,创建一个连接,输入测试用的mqtt
这里的MQTT的版本最好和代码里面的一致.选择版本是3.1.1,5.0的版本我看插件的源码里有些API是不支持的.
ini
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
MqttServerClient client = MqttServerClient.withPort(
"ws://172.16.14.201:8083/mqtt", 'flutter_client', "8083");
client.logging(on: true);
client.useWebSocket = true;
client.autoReconnect = true;
client.keepAlivePeriod = 60;
client.connectTimeoutPeriod = 5000;
client.onConnected = onConnected;
client.onDisconnected = onDisconnected;
client.onUnsubscribed = onUnsubscribed;
client.onSubscribed = onSubscribed;
client.onSubscribeFail = onSubscribeFail;
client.pongCallback = pong;
final connMess = MqttConnectMessage()
.withWillTopic('willtopic')
.withWillMessage('My Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMess;
try {
debugPrint('Connecting');
await client.connect();
} catch (e) {
debugPrint('Exception: $e');
client.disconnect();
}
我在调试的过程中,踩了两个坑,一是url,没有填完成,我写成了"172.16.14.201:8083/mqtt"
缺少了"ws://"
,其次是端口号写错了.这点官方是有解释的.
diff
- Broker: broker.emqx.io
- TCP Port: 1883
- Websocket Port: 8083
因为这两个地方写错了,导致一直无法建立连接. 还有就是MQTT对象的生命周期维护,最开始是通过Future异步返回一个MQTT对象,但是在主页面监听时,这个mqtt对象的生命周期已经结束了,导致对象一直是NULL,所以也无法建立连接.解决办法是尽量使这个mqtt对象是一个全局的.当然pop后断开连接,MQTT对象也释放掉. 注意以上这几点,应该是可以成功订阅\监听消息的.