connect method

Future<void> connect({
  1. Duration? timeout,
})

Establishes a TCP connection and initializes the transport codec.

If the codec specifies a PacketCodec.tag, it is written immediately after connecting.

Implementation

Future<void> connect({Duration? timeout}) async {
  timeout ??= const Duration(seconds: 10);
  _log.info('Connecting to $ip:$port/DC$dcId...');

  _socket = await Socket.connect(ip, port, timeout: timeout);
  _codec = createCodec();
  _connected = true;

  final tag = _codec.tag;
  if (tag != null) {
    _socket!.add(tag);
    await _socket!.flush();
  }

  _socketSub = _socket!.listen(
    (data) => _reader.addData(data),
    onError: (error) {
      _log.warning('Socket error: $error');
      _connected = false;
    },
    onDone: () {
      _log.fine('Socket closed by remote');
      _connected = false;
      _reader.close();
    },
  );

  _log.info('Connected to $this');
}