From 7a63be7ff04a62c399cdbe00b1ea585321bda646 Mon Sep 17 00:00:00 2001 From: Dario Varriale Date: Mon, 16 Sep 2024 09:54:10 +0200 Subject: [PATCH] Refactor connection handling and add support for WebSocket --- lib/mqtt5_client.dart | 1 + .../mqtt_connection_base.dart | 23 ++++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/mqtt5_client.dart b/lib/mqtt5_client.dart index f9e3c5e..68ba62d 100644 --- a/lib/mqtt5_client.dart +++ b/lib/mqtt5_client.dart @@ -9,6 +9,7 @@ library mqtt5_client; import 'dart:async'; import 'dart:convert'; +import 'dart:io'; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'package:typed_data/typed_data.dart' as typed; diff --git a/lib/src/connectionhandling/mqtt_connection_base.dart b/lib/src/connectionhandling/mqtt_connection_base.dart index aa11fd0..8edba67 100644 --- a/lib/src/connectionhandling/mqtt_connection_base.dart +++ b/lib/src/connectionhandling/mqtt_connection_base.dart @@ -76,10 +76,27 @@ class MqttConnectionBase { void _disconnect() { // On disconnect clean(discard) anything in the message stream messageStream.clean(); - if (client != null) { - client.destroy(); - client = null; + + // Close the client + if (client == null) { + return; } + + if (client is WebSocket) { + final wsClient = client as WebSocket; + wsClient.close(); + } else if (client is Socket) { + final socketClient = client as Socket; + socketClient.destroy(); + } else { + try { + client.destroy(); + } catch (e) { + MqttLogger.log('MqttConnectionBase::_disconnect - exception raised $e'); + } + } + + client = null; } /// User requested or auto disconnect disconnection