connect method
Future<void>
connect(
)
override
Implementation
@override
Future<void> connect() async {
// print('connecting');
try {
_socket = WebSocketChannel.connect(
Uri.parse('$url&useOnCloseEvent=true'),
);
} catch (e) {
throw ReownCoreError(
code: -1,
message: 'No internet connection: ${e.toString()}',
);
}
// Create a multi-subscription capable stream channel using stream splitting
// This approach enables multiple listeners without broadcast streams
_inputController = StreamController<String>.broadcast(sync: true);
_outputController = StreamController<String>.broadcast(sync: true);
// Split the incoming stream to support multiple listeners
_inputSubscription = _socket!.stream.cast<String>().listen(
(data) => _inputController?.add(data),
onError: (error) {
try {
_inputController?.addError(error);
} catch (e) {
debugPrint('[WebSocketHandler] inputController.addError failed: $e');
}
},
onDone: () {
try {
_inputController?.close();
} catch (e) {
debugPrint('[WebSocketHandler] inputController.close failed: $e');
}
},
);
// Route outgoing messages through the output controller
_outputSubscription = _outputController!.stream.listen(
(data) {
try {
_socket?.sink.add(data);
} catch (e) {
debugPrint('[WebSocketHandler] sink.add failed: $e');
}
},
onError: (error) {
try {
_socket?.sink.addError(error);
} catch (e) {
debugPrint('[WebSocketHandler] sink.addError failed: $e');
}
},
onDone: () {
try {
_socket?.sink.close();
} catch (e) {
debugPrint('[WebSocketHandler] sink.close failed: $e');
}
},
);
_channel = StreamChannel(_inputController!.stream, _outputController!.sink);
if (_channel == null) {
// print('Socket channel is null, waiting...');
await Future.delayed(const Duration(milliseconds: 500));
if (_channel == null) {
// print('Socket channel is still null, throwing ');
throw Exception('Socket channel is null');
}
}
try {
await _socket?.ready;
} catch (e) {
await close();
throw ReownCoreError(
code: -1,
message: 'WebSocket connection failed: ${e.toString()}',
);
}
}