connect method

  1. @override
Future<String?> connect(
  1. String url, {
  2. SocketConnectionOptions? options,
})
override

Connects to the socket server.

Throws SocketConnectionException if connection fails. Throws SocketTimeoutException if connection times out. Throws SocketInvalidUrlException if URL is invalid.

Implementation

@override
Future<String?> connect(String url, {SocketConnectionOptions? options}) async {
  try {
    // Validate URL
    if (url.isEmpty) {
      throw SocketInvalidUrlException('URL cannot be empty');
    }

    final uri = Uri.tryParse(url);
    if (uri == null ||
        (!uri.hasScheme || (!uri.scheme.startsWith('http') && !uri.scheme.startsWith('ws')))) {
      throw SocketInvalidUrlException('Invalid URL format: $url');
    }

    final data = <String, dynamic>{'url': url};
    if (options != null) {
      data.addAll({'options': options.toMap()});
    }

    final result = await methodChannel.invokeMethod<String>('connect', data);
    return result;
  } on PlatformException catch (e) {
    _handlePlatformException(e, 'connect');
  } catch (e) {
    if (e is SocketException) {
      rethrow;
    }
    throw SocketConnectionException('Unexpected error during connection: $e');
  }
}