#flutter #dart #mqtt
Вопрос:
Я получаю сообщение об ошибке при подключении к серверу Mosquitto в моем веб-проекте flutter. Я использую импорт для mqtt_browser_client.dart
и пакет mqtt_client.
Мой код следует примеру, и я проверил, могу ли я подключиться к своему серверу с того же компьютера в MQTT Explorer. (бекартпи:8080).
final client = MqttBrowserClient('ws://becArtPi', 'flutter');
void onPRessMQTTTest() async {
client.onDisconnected = onDisconnected;
client.onConnected = onConnected;
client.onSubscribed = onSubscribed;
client.logging(on: true);
client.port = 8080;
client.keepAlivePeriod = 20;
final connMess = MqttConnectMessage()
.withClientIdentifier('flutter')
.startClean() // Non persistent session for testing
.withWillQos(MqttQos.atLeastOnce);
print('EXAMPLE::Mosquitto client connecting....');
client.connectionMessage = connMess;
try {
await client.connect();
} on NoConnectionException catch (e) {
// Raised by the client when connection fails.
print('EXAMPLE::client exception - $e');
client.disconnect();
} on SocketException catch (e) {
// Raised by the socket layer
print('EXAMPLE::socket exception - $e');
client.disconnect();
} catch (e) {
print('MQTT Connection Error: $e');
}
client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
final recMess = c![0].payload as MqttPublishMessage;
final pt =
MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
print(
'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
print('');
});
/// Check we are connected
if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('EXAMPLE::Mosquitto client connected');
} else {
/// Use status here rather than state if you also want the broker return code.
print(
'EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${client.connectionStatus}');
client.disconnect();
exit(-1);
}
const pubTopic = 'Dart/Mqtt_client/testtopic';
final builder = MqttClientPayloadBuilder();
client.publishMessage(pubTopic, MqttQos.exactlyOnce, builder.payload!);
}
void onDisconnected() {}
void onConnected() {
print(
'EXAMPLE::OnConnected client callback - Client connection was sucessful');
}
void onSubscribed(String topic) {}
EXAMPLE::Mosquitto client connecting....
1-2021-08-18 15:23:35.899 -- MqttClient::connect - keep alive is enabled with a value of 20 seconds
1-2021-08-18 15:23:35.900 -- MqttConnectionKeepAlive:: Initialised with a keep alive value of 20 seconds
1-2021-08-18 15:23:35.900 -- MqttConnectionKeepAlive:: Disconnect on no ping response is disabled
1-2021-08-18 15:23:35.901 -- MqttConnectionHandlerBase::connect - server ws://becArtPi/ws, port 8080
1-2021-08-18 15:23:35.901 -- SynchronousMqttBrowserConnectionHandler::internalConnect entered
1-2021-08-18 15:23:35.901 -- SynchronousMqttBrowserConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
1-2021-08-18 15:23:35.902 -- SynchronousMqttBrowserConnectionHandler::internalConnect - calling connect
1-2021-08-18 15:23:35.902 -- MqttBrowserWsConnection::connect - entered
1-2021-08-18 15:23:35.903 -- MqttBrowserWsConnection::connect - WS URL is ws://becartpi:8080/ws
1-2021-08-18 15:23:35.906 -- MqttBrowserWsConnection::connect - connection is waiting
1-2021-08-18 15:23:36.068 -- MqttBrowserWsConnection::connect - websocket has erred
1-2021-08-18 15:23:36.069 -- SynchronousMqttBrowserConnectionHandler::internalConnect - connection complete
1-2021-08-18 15:23:36.069 -- SynchronousMqttBrowserConnectionHandler::internalConnect sending connect message
1-2021-08-18 15:23:36.069 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 0
Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=20
MqttConnectPayload - client identifier is : flutter
1-2021-08-18 15:23:36.072 -- SynchronousMqttBrowserConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
1-2021-08-18 15:23:41.098 -- SynchronousMqttBrowserConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
1-2021-08-18 15:23:41.099 -- SynchronousMqttBrowserConnectionHandler::internalConnect - initiating connection try 1, auto reconnect in progress false
1-2021-08-18 15:23:41.099 -- SynchronousMqttBrowserConnectionHandler::internalConnect - calling connect
1-2021-08-18 15:23:41.099 -- MqttBrowserWsConnection::connect - entered
1-2021-08-18 15:23:41.100 -- MqttBrowserWsConnection::connect - WS URL is ws://becartpi:8080/ws
1-2021-08-18 15:23:41.100 -- MqttBrowserWsConnection::connect - connection is waiting
1-2021-08-18 15:23:41.276 -- MqttBrowserWsConnection::connect - websocket has erred
1-2021-08-18 15:23:41.276 -- SynchronousMqttBrowserConnectionHandler::internalConnect - connection complete
1-2021-08-18 15:23:41.276 -- SynchronousMqttBrowserConnectionHandler::internalConnect sending connect message
1-2021-08-18 15:23:41.277 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 21
Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=20
MqttConnectPayload - client identifier is : flutter
1-2021-08-18 15:23:41.277 -- SynchronousMqttBrowserConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
1-2021-08-18 15:23:46.318 -- SynchronousMqttBrowserConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
1-2021-08-18 15:23:46.318 -- SynchronousMqttBrowserConnectionHandler::internalConnect - initiating connection try 2, auto reconnect in progress false
1-2021-08-18 15:23:46.319 -- SynchronousMqttBrowserConnectionHandler::internalConnect - calling connect
1-2021-08-18 15:23:46.319 -- MqttBrowserWsConnection::connect - entered
1-2021-08-18 15:23:46.319 -- MqttBrowserWsConnection::connect - WS URL is ws://becartpi:8080/ws
1-2021-08-18 15:23:46.320 -- MqttBrowserWsConnection::connect - connection is waiting
1-2021-08-18 15:23:46.487 -- MqttBrowserWsConnection::connect - websocket has erred
1-2021-08-18 15:23:46.487 -- SynchronousMqttBrowserConnectionHandler::internalConnect - connection complete
1-2021-08-18 15:23:46.487 -- SynchronousMqttBrowserConnectionHandler::internalConnect sending connect message
1-2021-08-18 15:23:46.488 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 21
Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=20
MqttConnectPayload - client identifier is : flutter
1-2021-08-18 15:23:46.488 -- SynchronousMqttBrowserConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
1-2021-08-18 15:23:51.521 -- SynchronousMqttBrowserConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
1-2021-08-18 15:23:51.522 -- SynchronousMqttBrowserConnectionHandler::internalConnect failed
EXAMPLE::client exception - mqtt-client::NoConnectionException: The maximum allowed connection attempts ({3}) were exceeded. The broker is not responding to the connection request message (Missing Connection Acknowledgement?
1-2021-08-18 15:23:51.523 -- MqttConnectionHandlerBase::disconnect - entered
1-2021-08-18 15:23:51.523 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered
Подключение в проводнике MQTT, который правильно подключается и получает сообщения.
комары.журнал
1629283989: Socket error on client 8caab5860e74, disconnecting.
1629284712: Socket error on client <unknown>, disconnecting.
1629284717: Socket error on client <unknown>, disconnecting.
1629284722: Socket error on client <unknown>, disconnecting.
Комментарии:
1. Что есть в журналах комаров за тот же период?
2. @hardillb Супер нехорошо…
1629284722: Socket error on client <unknown>, disconnecting.
Ответ №1:
Проверьте настройки API заголовков websocket.Возможно, вы отправляете неправильные заголовки для своего брокера.
Взгляните на mqtt_server_client_websocket.файл dart в каталоге примеров, параметр, который вы хотите, — client.websocketProtocols, посмотрите на API для этого.
Комментарии:
1. Спасибо @user2685314. Я изучил API, и мне ничего не известно о том, как бы я это сделал или каковы мои варианты.
2. Решение действительно состояло в том, чтобы определить протокол websocket:
client.websocketProtocols = ['mqtt'];
3. этот пост действительно помогает