sendMessage method

  1. @override
Future<void> sendMessage(
  1. Message message, {
  2. bool attemptReconnect = true,
})
override

Send a message to the server

If attemptReconnect is true, then the client will attempt to reconnect on connection error

Implementation

@override
Future<void> sendMessage(
  Message message, {
  bool attemptReconnect = true,
}) async {
  if (_connectionStatusValue.isDisconnected || _transport == null) {
    throw StateError('Client not connected');
  }

  final data = _messageCodec.encode(message);

  // ignore: prefer_asserts_with_message assert function
  assert(() {
    if (data == null) {
      throw StateError(
        '[WebSocketClient] cannot send a message that cannot be encoded.'
        ' Have you added the plugin to the client?'
        '\nMessage: $message',
      );
    }
    return true;
  }());

  if (data == null) {
    return;
  }

  try {
    await _transport!.send(data);

    if (await _handshakeCompleted) {
      _updateConnectionStatus(ConnectionStatus.connected);
    }
  } catch (e) {
    _handleTransportError(
      e,
      attemptReconnect: attemptReconnect,
    );
    rethrow;
  }
}