我使用 mqqtx工具测试是没有问题的,但是我用自己的代码的时候就出现了问题
配置如下:
String cerData = await rootBundle.loadString("assets/images/ca.pem");
List<int> certAsBytes = utf8.encode(cerData);
final context = SecurityContext.defaultContext;
context.setTrustedCertificatesBytes(certAsBytes);
/// Set secure working
client.secure = false;
// Set the port
client.port = 8883; // Secure port number for mosquitto, no client certificate required
/// Security context
//final currDir = '${path.current}${path.separator}files${path.separator}ca.pem';
//final context = SecurityContext.defaultContext;
// Note if you get a 'TlsException: Failure trusting builtin roots (OS Error:
// CERT_ALREADY_IN_HASH_TABLE' error here comment out the following 2 lines
//context
//.setTrustedCertificates(currDir);
// 心跳时间 保持一分钟连接
client.keepAlivePeriod = 60;
// 设置协议版本,默认是3.1,根据服务器需要的版本来设置
client.setProtocolV311();
// 是否打印mqtt日志信息
client.logging(on: true);
// 连接断开回调
client.onDisconnected = onDisconnected;
// 订阅成功回调
client.onSubscribed = onSubscribed;
// 取消订阅回调
client.onUnsubscribed = _onUnSubscribed;
// 默认clientID
//client.clientIdentifier = clientId;
//client.onBadCertificate = (Object a) => true;
final connMess = MqttConnectMessage()
.withClientIdentifier('mqttx_42bd9sf345')
.withWillTopic('sensor/deviceState') // If you set this you must set a will message
.withWillMessage('My Will message')
.authenticateAs("admin", "admin")
.startClean() // Non persistent session for testing
.withProtocolName("MQTT")
//.withProtocolVersion(4)
.withWillQos(MqttQos.atLeastOnce);
print('EXAMPLE::Mosquitto client connecting....');
client.connectionMessage = connMess;
//final connMess = MqttConnectMessage();
//设置will消息的qos模式 0 1 2 选择0
//connMess.withWillQos(MqttQos.atMostOnce);
//连接MQTT服务器
try {
await client.connect();
//connectMessage = "你好";
} on Exception catch (e) {
print('---------连接失败: - ${e.toString()}');
client.disconnect();
//connectMessage = e.toString();
}
错误如下
[error] supervisor: 'esockd_connection_sup - <0.374.0>', errorContext: connection_shutdown, reason: {ssl_error,{tls_alert,{unexpected_message,"TLS server: In state hello at tls_record.erl:564 generated SERVER ALERT: Fatal - Unexpected Message\n {unsupported_record_type,16}"}}}, offender: [{pid,<0.1064.0>},{name,connection},{mfargs,{emqx_connection,start_link,[[{deflate_options,[]},{max_conn_rate,500},{active_n,100},{zone,external},{proxy_address_header,<<>>},{proxy_port_header,<<>>},{supported_subprotocols,[]}]]}}]