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.
Implementation
Future<void> connect() async {
try {
_socket = await WebSocket.connect(serverUrl);
debugPrint('Connected to WebSocket server: $serverUrl');
// Listen for incoming messages and handle them appropriately.
_socket?.listen(
(data) {
// Check the type of incoming data and call the appropriate callback.
if (data is String) {
onMessageReceived(data); // Handle text messages.
} else if (data is Uint8List) {
fileCallBackFunction(data); // Handle binary file data.
debugPrint("Stream data detected");
} else {
debugPrint("Received unsupported data type: ${data.runtimeType}");
}
},
onDone: () {
debugPrint('WebSocket connection closed.');
_socket = null; // Clear the socket instance.
_pingTimer?.cancel();
_pingTimer = null;
},
onError: (error) {
debugPrint('Error: $error');
onError?.call(error); // Call the error callback if provided.
_socket = null; // Clear the socket instance.
_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 WebSocket server: $e');
}
}