connect method
Connects to the WebSocket server.
This method establishes a WebSocket connection to the specified server URL. If the connection is successful, it listens for incoming messages and errors. Prints a message to the console when the connection is established or if it fails.
Throws an Exception if the connection fails.
Implementation
Future<void> connect() async {
try {
_socket = await WebSocket.connect(serverUrl);
debugPrint('Connected to Audio WebSocket server: $serverUrl');
_socket?.listen(
(data) {
switch (data.runtimeType.toString()) {
case '_Uint8ArrayView':
Uint8List byteData = Uint8List.fromList(data);
audioCallBackFunction(byteData);
debugPrint("Stream data detected");
break;
default:
debugPrint("Type of data = ${data.runtimeType}");
}
},
onDone: () {
debugPrint('Audio WebSocket connection closed.');
_socket = null;
_pingTimer?.cancel();
_pingTimer = null;
},
onError: (error) {
debugPrint('Error: $error');
if (onError != null) {
onError!(error);
}
_socket = null;
_pingTimer?.cancel();
_pingTimer = null;
},
);
_pingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
if (_socket != null && _socket!.readyState == WebSocket.open) {
_socket!.add('ping');
debugPrint('Ping sent to server.');
}
});
} catch (e) {
debugPrint('Failed to connect to Audio WebSocket server: $e');
}
}