connect method

Future<bool> connect({
  1. bool forceReconnect = false,
})

Implementation

Future<bool> connect({bool forceReconnect = false}) async {
  // cannot connect to an invalid uri
  if (uri == null) {
    Log().error('SOCKET:: Uri has not been set. Cannot connect');
    return false;
  }

  try {
    // connect to the socket
    if (!connected || forceReconnect) {
      Log().debug('SOCKET:: Connecting to $url');

      lastMessage = null;

      // close the old socket
      if (_socket != null) await _socket!.sink.close();

      // connect
      connected = false;
      _socket = WebSocketChannel.connect(uri!);
      connected = true;

      Log().debug('SOCKET:: Connected');

      // listen for messages
      _socket!.stream.listen(_onData, onError: _onError, onDone: _onDone);

      // notify listener of connection
      listener.onConnected();
    }
  } catch (e) {
    connected = false;
    Log().error('SOCKET:: Error Connecting to $url. Error is $e');
  }
  return connected;
}