write method

  1. @override
Future<void> write(
  1. Uint8List data
)
override

Writes data to the connection.

Implementation

@override
Future<void> write(Uint8List data) async {
  _assertNotClosed();
  await _writeLock.synchronized(() async {
    if (_closed) { // Re-check after acquiring lock
      _log.finer('TCPConnection($id) - Write aborted, connection closed while waiting for lock.');
      throw StateError('Connection is closed (id: $_id)');
    }
    try {
      final dataHex = hex.encode(data); // Encode once for logging
      _log.finer('TCPConnection.write (id: $id): Writing ${data.length} bytes: $dataHex');
      _socket.add(data);
      await _socket.flush();
      _log.finest('TCPConnection.write (id: $id): Flushed ${data.length} bytes successfully. Data preview (hex): ${dataHex.substring(0, dataHex.length > 40 ? 40 : dataHex.length)}...');
    } catch (e) {
      _log.finer('TCPConnection($id) - Error during socket write/flush: $e. Closing connection.');
      // Avoid calling close() again if already closing due to another error or from another write
      if (!_closed) {
        await close();
      }
      rethrow;
    }
  });
}