connect method

  1. @override
void connect()
override

Implementation

@override
void connect() async {
  logger.debug('connect()');

  if (_url == null) {
    throw AssertionError('Invalid argument: _url');
  }

  if (isConnected()) {
    logger.debug('WebSocket $_url is already connected');
    return;
  } else if (isConnecting()) {
    logger.debug('WebSocket $_url is connecting');
    return;
  }
  if (_ws != null) {
    disconnect();
  }
  logger.debug('connecting to WebSocket $_url');
  try {
    _ws = WebSocketImpl(_url!);

    _ws!.onOpen = () {
      _closed = false;
      _connected = true;
      logger.debug('Web Socket is now connected');
      _onOpen();
    };

    _ws!.onMessage = (dynamic data) {
      _onMessage(data);
    };

    _ws!.onClose = (int? closeCode, String? closeReason) {
      logger.debug('Closed [$closeCode, $closeReason]!');
      _connected = false;
      _onClose(true, closeCode, closeReason);
    };

    _ws!.connect(
        protocols: <String>[_websocket_protocol],
        webSocketSettings: _webSocketSettings);
  } catch (e, s) {
    Log.e(e.toString(), null, s);
    _connected = false;
    logger.error('WebSocket $_url error: $e');
  }
}