mirror of
https://github.com/chenasraf/ctelnet_dart.git
synced 2026-05-18 01:49:04 +00:00
feat: timeout
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -5,3 +5,6 @@
|
||||
# Avoid committing pubspec.lock for library packages; see
|
||||
# https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
pubspec.lock
|
||||
|
||||
# secrets
|
||||
.env
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:ctelnet/ctelnet.dart';
|
||||
|
||||
void main(List<String> 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<String> args) async {
|
||||
print('Connecting to $host:$port');
|
||||
|
||||
final client = CTelnetClient(
|
||||
@@ -20,6 +23,6 @@ void main(List<String> args) async {
|
||||
|
||||
client.send('Hello, world!');
|
||||
|
||||
// await client.disconnect();
|
||||
await client.disconnect();
|
||||
}
|
||||
|
||||
@@ -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<RawSocket> _task;
|
||||
|
||||
bool _isConnected = false;
|
||||
|
||||
StreamSubscription<RawSocketEvent>? _subscription;
|
||||
@@ -60,6 +63,7 @@ class CTelnetClient implements ITelnetClient {
|
||||
Future<void> 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<void> 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
|
||||
|
||||
Reference in New Issue
Block a user