shamblett/mqtt_client

Failed to connect to mqtt, I don’t know where the problem lies

Closed this issue · 1 comments

I/flutter ( 3528): 1-2024-03-14 19:20:32.340702 -- MqttClient::connect - Connection timeout period is 5000 milliseconds
I/flutter ( 3528): 1-2024-03-14 19:20:32.346077 -- MqttClient::connect - keep alive is disabled
I/flutter ( 3528): 1-2024-03-14 19:20:32.347625 -- MqttConnectionHandlerBase::connect - server test.mqtt.com, port 32546
I/flutter ( 3528): 1-2024-03-14 19:20:32.349884 -- SynchronousMqttServerConnectionHandler::internalConnect entered
I/flutter ( 3528): 1-2024-03-14 19:20:32.350413 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
I/flutter ( 3528): 1-2024-03-14 19:20:32.350778 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter ( 3528): 1-2024-03-14 19:20:32.351364 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
I/flutter ( 3528): 1-2024-03-14 19:20:32.352038 -- MqttNormalConnection::connect - entered
I/flutter ( 3528): --------------------Instance of 'XMqttClient'
I/flutter ( 3528): 1-2024-03-14 19:20:32.482934 -- MqttServerConnection::_startListening
I/flutter ( 3528): 1-2024-03-14 19:20:32.485095 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter ( 3528): 1-2024-03-14 19:20:32.485327 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter ( 3528): 1-2024-03-14 19:20:32.486026 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter ( 3528): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 0
I/flutter ( 3528): Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=true, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=true, UserNameFlag=true, KeepAlive=0
I/flutter ( 3528): MqttConnectPayload - client identifier is : 1710415232327asc
I/flutter ( 3528): 1-2024-03-14 19:20:32.495283 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none

``
When the connection is started, the above error log will be reported. The parameters I connected in vue3 are different from the parameters in flutter.

This is flutter's
static const host = 'test.mqtt.com'; // 替换成你自己的主机 static const port = 32546; // 端口号 static const user = 'admin'; // 用户 static const pwd = '123@123'; // 密码 List<String> topics = ['mqtt/pre/test'];
This is vue3
const String host= "test.mqtt.com"; const String password= "123@123"; const String port= 32546; const String reconnectPeriod= 4000, ; const String username= "admin"; const String endpoint= "/mqtt"; const String protocol= "ws"; const String sub_topic= "mqtt/pre/test";
This is the complete configuration
`import 'dart:convert';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class XMqttClient {
static final XMqttClient instance = XMqttClient.();
static XMqttClient get instance => instance;
static const host = 'test.mqtt.com'; // 替换成你自己的主机
static const port = 32546; // 端口号
static const user = 'admin'; // 用户
static const pwd = '123@123'; // 密码
List topics = ['mqtt/pre/test'];
MqttClient? client;
XMqttClient.
() {
print('-----------------------------------连接开始---------------------------------------');
_initMqtt();
}

_initMqtt() async {
// clientld 确保唯一性,否则如果两台机器的clientld 相同 则会连上立刻断开连接!!!
String clientId = '${DateTime.now().millisecondsSinceEpoch}asc';

client = await connect(clientId);

}

Future connect(String cid) async {
print('mqtt 连接 主机 = $host 客户端id = $cid');
MqttServerClient client = MqttServerClient.withPort(host, cid, port);
client.logging(on: true);
client.onConnected = onConnected;
client.onDisconnected = onDisconnected;
client.onUnsubscribed = onUnsubscribed;
client.onSubscribed = onSubscribed;
client.onSubscribeFail = onSubscribeFail;
client.pongCallback = pong;

final connMessage = MqttConnectMessage()
    .authenticateAs(user, pwd)
    .keepAliveFor(6000) // 保持连接时间,单位为秒
    .withWillTopic('willtopic')
    .withWillMessage('ss')
    .startClean() // 清理会话
    .withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMessage;
try {
  print(123123);
  await client.connect();
} catch (e) {
  print('连接异常: $e');
  client.disconnect();
}

// 用于监听已订阅主题的消息到达。
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
  final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
  final String pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
  // 解码包含中文字符的字符串
  final String decodedString = utf8.decode(pt.codeUnits);

  print('接收到消息: $decodedString 来自主题: ${c[0].topic}');
});

return client;

}

/// 订阅一个主题
_subscribe(String topic) {
client?.subscribe(topic, MqttQos.atLeastOnce);
}

/// 订阅多个主题
topicSubscribe(List topics) async {
this.topics.addAll(topics);

if (client?.connectionStatus?.state == MqttConnectionState.connected) {
  topics.forEach((topic) {
    _subscribe(topic);
  });
} else {
  // 未连接成功 每隔3s重新订阅
  Future.delayed(const Duration(seconds: 3), () {
    topicSubscribe(topics);
  });
}

}

/// 取消订阅
_unsubscribe() {
client?.unsubscribe('mqtt/pre/alertRefreshTopic');
}

/// 断开连接
_disconnect() {
client?.disconnect();
}

// 连接成功
void onConnected() {
print('-----------------------------------连接成功---------------------------------------');
}

// 连接断开
void onDisconnected() {
print('-----------------------------------连接断开---------------------------------------');
}

// 订阅主题成功
void onSubscribed(String topic) {
print('订阅主题成功: $topic');
}

// 订阅主题失败
void onSubscribeFail(String topic) {
print('订阅主题失败 $topic');
}

// 成功取消订阅
void onUnsubscribed(String? topic) {
print('成功取消订阅: $topic');
}

// 收到 PING 响应
void pong() {
print('收到 PING 响应 调用Ping响应客户端回调');
}
}
`

Is it because of this? If not, what is the problem?I hope you can help me. Thank you.

So are you saying one set of settings works and the other doesn't? Its not clear to me, what is vue3?

You are connecting and sending the connect message -

I/flutter ( 3528): 1-2024-03-14 19:20:32.485095 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter ( 3528): 1-2024-03-14 19:20:32.485327 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message

If you are being disconnected at this point the broker doesn't like the connection message.

A few things to note -

Are you using the correct MQTT version, most brokers use the 3.1.1 protocol so you need to set version311 on the client.

Not sure what the 'protocols = ws' means in the vue3 settings, you are using the server client, if you want to use web sockets you must set this selection on the client.

A few things to do -

Trim your connection message down to the basics i.e. username and password, get rid of all the will stuff for instance, if it starts working add stuff back in till it fails, this will tell you where the fault is.

Examine your broker logs, there should be an entry in them showing why your client connection was refused.