connect method

Future<void> connect()

Connect to the peer

Implementation

Future<void> connect() async {
  if (_state != ConnectionState.disconnected) {
    throw ConnectionException('Connection already in progress or established');
  }

  _setState(ConnectionState.connecting);
  logger.info('Connecting to $address:$port...');

  try {
    // Establish TCP connection with timeout
    _socket = await Socket.connect(address, port)
      .timeout(config.connectTimeout);

    // Set socket options
    _socket!.setOption(SocketOption.tcpNoDelay, true);

    // Start listening for data
    _socketSubscription = _socket!.listen(
      _onDataReceived,
      onError: _onSocketError,
      onDone: _onSocketClosed,
    );

    _connectedAt = DateTime.now();
    _setState(ConnectionState.connected);

    // Start message send loop AFTER connection is established
    _startSendLoop();

    logger.info('Connected to $address:$port');

  } catch (e) {
    final error = ConnectionException('Failed to connect to $address:$port', e);
    _setState(ConnectionState.error);
    _errorController.add(error);
    throw error;
  }
}