sendMessage method

Future<bool> sendMessage(
  1. String text
)

Sends a chat message; waits for a live socket and retries briefly if needed.

Implementation

Future<bool> sendMessage(String text) async {
  final trimmed = text.trim();
  if (trimmed.isEmpty) return true;
  if (_disposed || !_started) return false;

  const maxAttempts = 4;
  for (var attempt = 0; attempt < maxAttempts; attempt++) {
    if (_disposed || !_started) return false;
    if (!isSocketOpen) {
      try {
        await _openSocket(reason: 'send:ensureOpen');
      } catch (_) {
        await Future<void>.delayed(Duration(milliseconds: 200 * (attempt + 1)));
        continue;
      }
    }
    if (!isSocketOpen) {
      await Future<void>.delayed(Duration(milliseconds: 200 * (attempt + 1)));
      continue;
    }
    final payload = <String, Object?>{
      'Action': 'SEND_MESSAGE',
      'RequestId': DateTime.now().millisecondsSinceEpoch.toString(),
      'Content': trimmed,
    };
    try {
      _ws!.add(jsonEncode(payload));
      return true;
    } catch (_) {
      _scheduleReconnect(trigger: 'sendFailed');
      await Future<void>.delayed(Duration(milliseconds: 250 * (attempt + 1)));
    }
  }
  return false;
}