connect method

  1. @override
Future connect({
  1. Duration? timeout = const Duration(seconds: 5),
})
override

connect let you connect to a network printer.

Sets TCP_NODELAY to disable Nagle's algorithm so small ESC/POS commands are sent immediately without waiting for more data.

Implementation

@override
Future connect({Duration? timeout = const Duration(seconds: 5)}) async {
  // Avoid opening multiple connections.
  if (isConnected) return;
  // Drop a socket that died since the last connect.
  if (socket != null) await disconnect();
  final address = printer.address;
  if (address == null || address.isEmpty) {
    return Future.error('Network printer has no address');
  }

  try {
    final s = await Socket.connect(
      address,
      printer.port ?? 9100,
      timeout: timeout ?? const Duration(seconds: 5),
    );
    socket = s;
    _socketError = null;
    _rx.clear();
    // Never leave socket.done / stream errors unhandled: an unhandled
    // socket error future crashes the isolate.
    s.done.catchError((Object e) {
      _socketError ??= e;
    });
    _sub = s.listen(
      (data) {
        _rx.addAll(data);
        final w = _rxWaiter;
        if (w != null && !w.isCompleted) w.complete();
      },
      onError: (Object e) {
        _socketError ??= e;
        final w = _rxWaiter;
        if (w != null && !w.isCompleted) w.complete();
      },
      onDone: () {
        _socketError ??= 'Socket closed by printer';
        final w = _rxWaiter;
        if (w != null && !w.isCompleted) w.complete();
      },
      cancelOnError: true,
    );
    // Disable Nagle's algorithm — send ESC/POS commands immediately
    // instead of buffering them. Critical for small writes like status
    // queries and cut commands.
    socket!.setOption(SocketOption.tcpNoDelay, true);
  } catch (e) {
    await disconnect();
    return Future.error('Failed to connect to ${printer.address}:${printer.port ?? 9100} — $e');
  }
}