From 4fee13812ccc2f242d153a76ef8b2bd8affca343 Mon Sep 17 00:00:00 2001 From: Chen Asraf Date: Fri, 22 Sep 2023 02:12:09 +0300 Subject: [PATCH] feat: timeout --- .gitignore | 3 +++ ...net_example.dart => simple_connection.dart} | 11 +++++++---- lib/src/client.dart | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) rename example/{ctelnet_example.dart => simple_connection.dart} (70%) diff --git a/.gitignore b/.gitignore index 3cceda5..ec3cabb 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ # Avoid committing pubspec.lock for library packages; see # https://dart.dev/guides/libraries/private-files#pubspeclock. pubspec.lock + +# secrets +.env diff --git a/example/ctelnet_example.dart b/example/simple_connection.dart similarity index 70% rename from example/ctelnet_example.dart rename to example/simple_connection.dart index 7776d25..fbeaa07 100644 --- a/example/ctelnet_example.dart +++ b/example/simple_connection.dart @@ -1,9 +1,12 @@ +import 'dart:io'; + import 'package:ctelnet/ctelnet.dart'; -void main(List args) async { - final host = String.fromEnvironment('HOST', defaultValue: 'localhost'); - final port = int.tryParse(String.fromEnvironment('PORT', defaultValue: '23')) ?? 23; +var env = Platform.environment; +final host = env['HOST'] ?? 'localhost'; +final port = int.parse(env['PORT'] ?? '23'); +void main(List args) async { print('Connecting to $host:$port'); final client = CTelnetClient( @@ -20,6 +23,6 @@ void main(List args) async { client.send('Hello, world!'); - // await client.disconnect(); + await client.disconnect(); } diff --git a/lib/src/client.dart b/lib/src/client.dart index 50f233a..c1a44f7 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -18,6 +18,7 @@ abstract class ITelnetClient { } class CTelnetClient implements ITelnetClient { + CTelnetClient({ required this.host, required this.port, @@ -51,6 +52,8 @@ class CTelnetClient implements ITelnetClient { late RawSocket _socket; + late ConnectionTask _task; + bool _isConnected = false; StreamSubscription? _subscription; @@ -60,6 +63,7 @@ class CTelnetClient implements ITelnetClient { Future connect() async { try { final task = await RawSocket.startConnect(host, port); + _task = task; _socket = await task.socket; _subscription = _socket.listen( _onData, @@ -71,6 +75,14 @@ class CTelnetClient implements ITelnetClient { } } + Future startTimeout() async { + await Future.delayed(timeout); + if (!_isConnected) { + _dispose(); + _onError(TimeoutException('Timeout for connection to $host:$port exceeded', timeout), StackTrace.current); + } + } + void _onData(RawSocketEvent event) { if (!_isConnected) { _isConnected = true; @@ -99,6 +111,12 @@ class CTelnetClient implements ITelnetClient { void _onDone() { onDisconnect(); _subscription?.cancel(); + _task.cancel(); + } + + void _dispose() { + _subscription?.cancel(); + _task.cancel(); } @override